标签:
/**
* 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反转,使用如下简单的方法。
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 p0 11 for(i=1;i<m;i++) 12 p0=p0->next; 13 p1=p0->next; 14 //reverse one by one 15 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 head 25 26 ListNode *p=newHead->next; 27 delete newHead; 28 return p; 29 } 30 };
Leetcode 92 Reverse Linked List ii
标签:
原文地址:http://www.cnblogs.com/zhuguanyu33/p/4423790.html