您的位置:首页 > 编程语言 > Java开发

[Leetcode] Reverse Linked List II (Java)

2014-01-17 14:39 323 查看
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的链表逆序

public class Solution {
public void reverse(ListNode pre,ListNode next){
ListNode last = pre.next;
ListNode cur = last.next;
while(cur!= next){
last.next = cur.next;
cur.next = pre.next;
pre.next = cur;
cur = last.next;
}
}

public ListNode reverseBetween(ListNode head, int m, int n) {
ListNode res = new ListNode(-1);
res.next = head;
int index = 1;
ListNode tmp = res;
while(tmp!=null&&index<m){
tmp = tmp.next;
index++;
}
ListNode pre = tmp;
while(tmp!=null&&index<n){
tmp = tmp.next;
index++;
}
tmp=tmp.next;
ListNode next=tmp.next;
reverse(pre, next);
return res.next;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: