码迷,mamicode.com
首页 > 其他好文 > 详细

Leetcode 92 Reverse Linked List ii

时间:2015-04-14 07:04:18      阅读:192      评论:0      收藏:0      [点我收藏+]

标签:

/**
* 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 reversed
ListNode 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 -> 5
for(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 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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!