Fork me on GitHub

92. Reverse Linked List II

92. 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 ≤ m ≤ n ≤ length of list.

解析

  • 1.通过构建新节点,避免从头开始反转讨论
  • 2.技巧就是向一个节点前面插入节点,指针每一次向前移动

class Solution_92 {
public:
	ListNode* reverseBetween(ListNode* head, int m, int n) {

		ListNode* newHead = new ListNode(0);
		newHead->next = head;

		ListNode* pre=NULL, *cur=newHead, *front=NULL;

		for (int i = 0; i < m - 1;i++)
		{
			cur = cur->next;
		}
		pre = cur;       //记录反转之前的节点
		ListNode* last = cur->next; //也是反转后的尾指针

		for (int i = m; i <= n;i++)
		{
			cur = pre->next;
			pre->next = cur->next;
			cur->next = front; //向front节点前插入,front每次前移
			front = cur;
		}

		cur = pre->next;
		pre->next = front;
		last->next = cur;

		return newHead->next;
	}
};

题目来源

posted @ 2018-04-12 21:56  ranjiewen  阅读(134)  评论(0编辑  收藏  举报