[Leetcode] Reverse Linked List II (Java)

来源:互联网 发布:油漆品牌 知乎 编辑:程序博客网 时间:2024/05/20 07:32

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->NULLm = 2 and n = 4,

return 1->4->3->2->5->NULL.

Note:
Given mn 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;}}


0 0
原创粉丝点击