Reverse a linked list from position m to n. Do it in one-pass.
Note: 1 ≤ m ≤ n ≤ length of list.
Example:
Input: 1->2->3->4->5->NULL, m = 2, n = 4 Output: 1->4->3->2->5->NULL
只反转从m到n的部分链表
M1: iterative
首先找到prev的位置(开始反转位置的前一个节点),cur为prev的后一个节点。然后开始反转,循环n-m次,在循环里,prev的位置始终保持不变,先保存cur下一个节点的位置,即nextnode,cur指向nextnode的下一个节点,nextnode指向prev的下一个节点,prev指向nextnode。
e.g.
1->2->3->4->5->NULL 2->4, 3->2, 1->3 => 1->3->2->4
p c n
1->3->2->4->5->NULL 2->5, 4->3, 1->4 => 1->4->3->2->5
p c n
1->4->3->2->5->NULL
p c n
time: O(n), space: O(1)
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */ class Solution { public ListNode reverseBetween(ListNode head, int m, int n) { int len = n - m; ListNode dummy = new ListNode(0); dummy.next = head; ListNode prev = dummy, cur = dummy.next; while(m > 1) { // find prev prev = prev.next; cur = cur.next; m--; } // return prev; while(len > 0) { ListNode nextnode = cur.next; cur.next = nextnode.next; nextnode.next = prev.next; prev.next = nextnode; len--; } return dummy.next; } }
原文地址:https://www.cnblogs.com/fatttcat/p/10122417.html
时间: 2024-11-05 18:39:24