反转链表
反转整个链表
1 2 3 4 5 6
| 示例:
Input: 1->2->3->4->5->NULL
Output: 5->4->3->2->1->NULL
|
全部代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45
| #include<iostream> #include <vector> using namespace std; struct ListNode{ int val; ListNode *next; ListNode(int x):val(x),next(NULL){} }; ListNode* createNodeList(const vector<int> & vec){ ListNode* prev = new ListNode(vec[0]); ListNode* prevHead = prev; for (int i = 1; i < vec.size(); i ++) { ListNode* next_node = new ListNode(vec[i]); prev -> next = next_node; prev = next_node; } return prevHead; } void ShowList(ListNode *l){ ListNode *p=l; while(p){ cout<<p->val<<" "; p=p->next; } cout<<endl; } class Solution{ public: ListNode* reverseList(ListNode* head) { if(head==NULL||head->next==NULL) return head; ListNode* res=reverseList(head->next); head->next->next=head; head->next=NULL; return res; } }; int main(){ vector<int> m1={1,2,3,4,5}; ListNode *l1=createNodeList(m1); Solution answer; ListNode *l2=answer.reverseList(l1); ShowList(l2); return 0; }
|
反转链表的前N个元素
1 2 3 4 5 6
| 示例:
Input: 1->2->3->4->5->NULL N=3
Output: 3->2->1->4->5->NULL
|
函数 reverseN(ListNode* head,int n)
的代码
1 2 3 4 5 6 7 8 9 10 11
| ListNode* last=NULL; ListNode* reverseN(ListNode* head,int n){ if(head==NULL||head->next==NULL||n==1) { last=head->next; return head; } ListNode* res=reverseN(head->next,n-1); head->next->next=head; head->next=last; return res; }
|
反转链表中m位置到n位置的元素
1 2 3 4 5 6
| 示例:
Input: 1->2->3->4->5->NULL M=2 N=4
Output: 1->4->3->2->5->NULL
|
函数 reverseBetween(ListNode* head,int m,int n)
的代码
1 2 3 4 5
| ListNode* reverseBetween(ListNode* head,int m,int n){ if(m==1) return reverseN(head,n); head->next=reverseBetween(head->next,m-1,n-1); return head; }
|