Reverse Linked List II

来源:互联网 发布:蜘蛛软件刷奖软件下载 编辑:程序博客网 时间:2024/06/16 06:14

Q:

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.


Solution:

Use a fake head to save the head position. Use prev to save the previous node position, because the current node needs to point to the previous node.

/** * Definition for singly-linked list. * public class ListNode { *     int val; *     ListNode next; *     ListNode(int x) { *         val = x; *         next = null; *     } * } */public class Solution {    public ListNode reverseBetween(ListNode head, int m, int n) {        if ( m == n)            return head;        ListNode fakeHead = new ListNode(0);        fakeHead.next = head;        ListNode before = fakeHead;        ListNode cur = head;        ListNode start = null;        ListNode end = null;        int count = 1;        while (count < m) {            before = before.next;            cur = cur.next;            count++;        }        start = cur;        ListNode prev = cur;        cur = cur.next;        while (count < n) {            ListNode q = cur.next;            cur.next = prev;            prev = cur;            cur = q;            count++;        }        before.next = prev;        start.next = cur;        return fakeHead.next;    }}


0 0
原创粉丝点击