Saturday, August 30, 2014

Reverse Linked List 2

Problem

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.

Idea

用两个pointer front 和 rear 分别指向 第m和第n元素,思路就是把m到n-1的元素加到n后面,然后把m到n-1删掉。 用个例子说明吧
1->2->3->4->5 m=2,n=4
  • 1->2->3->4->2->5
  • 1->2->3->4->3->2->5
  • 1->4->3->2->5

Solution


No comments:

Post a Comment