標籤:
/**
* ID: 92
* Name: Reverse Linked List
* Data Structure: Linked List
* Time Complexity:
* Space Complexity:
* Tag: LinkList
* Difficult: Medium
* Problem:
* Reverse a linked list from position m to n. Do it in-place and in one-pass.
* Given 1->2->3->4->5->NULL, m = 2 and n = 4.
* return 1->4->3->2->5->NULL.
* Given m, n satisfy the following condition
* 1 ≤ m ≤ n ≤ length of list
思路一:
發現用vector來處理linklist會方便了很多,然後思路一就是用vector來解決
思路二:
從m到n的node反轉,使用如下簡單的方法。
ListNode start = pre.next; // a pointer to the beginning of a sub-list that will be reversedListNode then = start.next;// a pointer to a node that will be reversed // 1 - 2 -3 - 4 - 5 ; m=2; n =4 ---> pre = 1, start = 2, then = 3// dummy-> 1 -> 2 -> 3 -> 4 -> 5for(inti=0; i<n-m; i++){ start.next = then.next; then.next = pre.next; pre.next = then; then = start.next;} 1-2-3-4 pre = 1, start = 2, then = 3把then 插入到pre的後面,pre不動,then始終在放到start的後面.start.next = then.next //把then先拿出來then.next = pre.next //把then在新位置上前後相連pre.next = then. // then的前面then = start.next // then 重新放到start的後面 思路一:
1 class Solution { 2 public: 3 ListNode *reverseBetween(ListNode *head, int m, int n) { 4 if(m==n || head == NULL) 5 return head; 6 std::vector<ListNode *> v; 7 ListNode *p = head; 8 while(p) 9 {10 v.push_back(p);11 p = p->next; 12 }13 int len = (n-m)/2+1;14 for(int i=0; i< len;i++)15 {16 ListNode * temp = v[i+m-1];17 v[i+m-1] = v[n-i-1];18 v[n-i-1] = temp; 19 20 }21 for(int i=0;i<v.size()-1;i++)22 v[i]->next = v[i+1];23 v[v.size()-1] ->next = NULL;24 return v[0];25 }26 };
思路二:
1 class Solution { 2 public: 3 ListNode *reverseBetween(ListNode *head, int m, int n) { 4 //make a head by myself 5 ListNode *newHead=new ListNode(0); 6 newHead->next=head; 7 ListNode *p0=newHead; 8 ListNode *p1=nullptr,*p2=nullptr; 9 int i;10 //find position of p011 for(i=1;i<m;i++)12 p0=p0->next;13 p1=p0->next;14 //reverse one by one15 while(i<n)16 {17 p2=p1->next;18 p1->next=p2->next;19 p2->next=p0->next;20 p0->next=p2;21 i++;22 }23 24 // p is the true head25 26 ListNode *p=newHead->next;27 delete newHead;28 return p;29 }30 };
Leetcode 92 Reverse Linked List ii