Skip to content

Latest commit

 

History

History
104 lines (78 loc) · 2.01 KB

20220523.md

File metadata and controls

104 lines (78 loc) · 2.01 KB

Algorithm

92. Reverse Linked List II

Description

Given the head of a singly linked list and two integers left and right where left <= right, reverse the nodes of the list from position left to position right, and return the reversed list.

Example 1:

Input: head = [1,2,3,4,5], left = 2, right = 4
Output: [1,4,3,2,5]

Example 2:

Input: head = [5], left = 1, right = 1
Output: [5]

Constraints:

  • The number of nodes in the list is n.
  • 1 <= n <= 500
  • -500 <= Node.val <= 500
  • 1 <= left <= right <= n

Follow up: Could you do it in one pass?

Solution

非递归

class Solution {
    public ListNode reverseBetween(ListNode head, int left, int right) {
        ListNode temp = new ListNode(0);
        temp.next = head;

        // 先移动left步
        ListNode cur1 = temp;
        ListNode pre1 = null;
        for(int i=0;i<left;i++){
             pre1 = cur1;
             cur1 = cur1.next;
        }
        //reverse
         ListNode cur2 = cur1;
         ListNode pre2 = pre1;
         for(int i=left;i<=right;i++){
             ListNode next = cur2.next;
             cur2.next = pre2;
             pre2 = cur2;
             cur2 = next;
         }

         //connect
         pre1.next = pre2;
         cur1.next = cur2;
         return temp.next;
    }
}

递归

class Solution {
    private ListNode successor = null;
    public ListNode reverseBetween(ListNode head, int left, int right) {
        if(left == 1){
            return reverseN(head, right);
        }
        head.next = reverseBetween(head.next, left - 1, right - 1);
        return head;
    }

    public ListNode reverseN(ListNode head, int n){
        if(n==1){
            successor = head.next;
            return head;
        }
        ListNode last = reverseN(head.next, n-1);
        head.next.next = head;
        head.next = successor;
        return last;
    }
}

Discuss

Review

Tip

Share