首页 > 其他 > 详细

LeetCode: Reverse Linked List

时间:2014-08-31 22:45:52      阅读:322      评论:0      收藏:0      [点我收藏+]

LeetCode: Reverse Linked List

Reverse a linked list from position m to n. Do it in-place and in one-pass.

For example:
Given 1->2->3->4->5->NULL, m = 2 and n = 4,

return 1->4->3->2->5->NULL.

Note:
Given m, n satisfy the following condition:
1 ≤ mn ≤ length of list.

地址:https://oj.leetcode.com/problems/reverse-linked-list-ii/

算法:先找到第m个节点p以及其前趋pre,然后把p记下,因为p是逆置链表部分的最后一个节点。然后从p开始遍历到第n个节点,并把节点依次插入pre后面,注意处理pre为空,也就是m=1的情况。代码:

 1 /**
 2  * Definition for singly-linked list.
 3  * struct ListNode {
 4  *     int val;
 5  *     ListNode *next;
 6  *     ListNode(int x) : val(x), next(NULL) {}
 7  * };
 8  */
 9 class Solution {
10 public:
11     ListNode *reverseBetween(ListNode *head, int m, int n) {
12         if(!head)   return NULL;
13         ListNode *pre = NULL;
14         ListNode *p = head;
15         int i = 1;
16         while(p && i != m){
17             pre = p;
18             p = p->next;
19             ++i;
20         }
21         if(!p)  return head;
22         ListNode *first_reverse_node = p;
23         if(pre){
24             pre->next = NULL;
25         }
26         ListNode *q = p;
27         while(q && i <= n){
28             q = p->next;
29             if(pre){
30                 p->next = pre->next;
31                 pre->next = p;
32             }else{
33                 if(p == head)
34                     head->next = NULL;
35                 else{
36                     p->next = head;
37                     head = p;
38                 }
39             }
40             p = q;
41             ++i;
42         }
43         first_reverse_node->next = q;
44         return head;
45     }
46 };

 

LeetCode: Reverse Linked List

原文:http://www.cnblogs.com/boostable/p/leetcode_reverse_linked_list.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!