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

14. Reverse Linked List II

时间:2014-08-25 01:07:43      阅读:198      评论:0      收藏:0      [点我收藏+]

标签:style   blog   os   io   strong   for   div   log   amp   

Reverse Linked List II

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.

 

总结:其实就是反转链表。不过是反转中间一部分。要注意的是保存第一个结点的前继的指针;  若第一个结点是头结点,注意反转子串的尾结点变为头结点。

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
 class Solution {
 public:
	 ListNode *reverseBetween(ListNode *head, int m, int n) {
		 ListNode *preNode1, *node1, *node2;
		 preNode1 = node1 = node2 = NULL;
		 int cnt = 0;
		 for(ListNode *p = head; p != NULL; p = p->next) {
			 cnt++;
			 if(cnt == m-1) preNode1 = p; // hidden: m > 1
			 if(cnt == m) node1 = p;
			 if(cnt == n) { node2 = p; break; }
		 }
		 ListNode *tail = node2->next; // must take out as a tag.
		 ListNode *pre = tail, *post;
		 while(node1 != tail) {
			 post = node1->next;
			 node1->next = pre;
			 pre = node1;
			 node1 = post;
		 }
		 if(m > 1) { preNode1->next = node2; return head;}
		 return node2; // node1 is the 1st node.
	 }
 };

 

14. Reverse Linked List II

标签:style   blog   os   io   strong   for   div   log   amp   

原文地址:http://www.cnblogs.com/liyangguang1988/p/3933965.html

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