92. Reverse Linked List II

yPhantom 2019年10月17日 30次浏览

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

Solution

题意让反转链表中从m到n的位置,还是用pre,cur,next三个结点。

关键在于保持pre结点不变,每次都让next结点的next指向pre的next。

Java版本

/**
 * 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) {
        ListNode dummy = new ListNode(-1);
        dummy.next = head;
        ListNode pre = dummy;
        for (int i = 0; i < m - 1; i++) {
            pre = pre.next;
        }
        if (pre == null || pre.next == null) {
            return dummy.next;
        }
        ListNode cur = pre.next;
        ListNode next = cur.next;
        for(int i = 0; i < n - m; i++) {
            cur.next = next.next;
            next.next = pre.next;
            pre.next = next;
            next = cur.next;
        }
        return dummy.next;
    }
}

Python3版本

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def reverseBetween(self, head: ListNode, m: int, n: int) -> ListNode:
        dummy = ListNode(-1)
        dummy.next = head
        
        pre = dummy
        for i in range(m - 1):
            pre = pre.next
        cur = pre.next
        post = cur.next
        
        for j in range(0, n - m):
            cur.next = post.next
            post.next = pre.next
            pre.next = post
            post = cur.next
        
        return dummy.next