- 描述
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.
- 思路
假如这道题不是链表而是数组旋转,那么思路就很清晰了,将第m个元素和第n个元素交换,第m+1跟第n-1个元素交换,直到m>=n。
但是这里给定的是链表,就不能像数组一样直接操作索引交换元素。
但是链表可以使用节点记录当前交换的位置P,然后通过相对的位置找到与P节点交换的节点R,交换元素后使p=p.next,继续交换,直到所有的元素交换结束,即完成了链表的旋转 - 代码(c#)
public ListNode ReverseBetween(ListNode head, int m, int n)
{
var h = head;
int index = 1;
while (index < m)//寻找第一个需要交换的元素
{
head = head.next;
index++;
}
Reverse(head, n - m);
return h;
}
public void Reverse(ListNode head, int end)//end为相对位置距离
{
var h = head;
if ( end>0)
{
int count = 0;
while (count < end)//寻找与p相交换的元素r
{
head = head.next;
count++;
}
var temp = h.val;
h.val = head.val;
head.val = temp;//交换元素
Reverse(h.next,end - 2);//交换下一个
}
}