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

LeetCode OJ - Reverse Linked List II

时间:2014-06-09 23:03:18      阅读:254      评论:0      收藏:0      [点我收藏+]

标签:c   style   class   blog   code   java   

题目:

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->NULLm = 2 and n = 4,

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

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

解题思路:

先找到需要翻转的起始节点,然后,翻转其后的n - m 个节点。 注意处理翻转的起始节点为head的情况。

代码:

bubuko.com,布布扣
 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 == NULL) return NULL;
13         
14         ListNode *pre_node = NULL, *mid_first = head;
15         for (int i = 1; i < m; i++) {
16             pre_node = mid_first;
17             mid_first = mid_first->next;
18         }
19         ListNode *last = mid_first->next, *pre = mid_first;
20         for (int i = m; i < n; i++) {
21             ListNode *tmp = last->next;
22             last->next = pre;
23             pre = last;
24             last = tmp;
25         }
26         if (pre_node == NULL) {
27             head = pre;
28             mid_first->next = last;
29         } else {
30             pre_node->next = pre;
31             mid_first->next = last;
32         }
33         return head;
34     }
35 };
bubuko.com,布布扣

 

LeetCode OJ - Reverse Linked List II,布布扣,bubuko.com

LeetCode OJ - Reverse Linked List II

标签:c   style   class   blog   code   java   

原文地址:http://www.cnblogs.com/dongguangqing/p/3775024.html

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