連結串列系列
阿新 • • 發佈:2021-11-24
92.Reverse Linked List II
Medium
Given thehead
of a singly linked list and two integersleft
andright
whereleft <= right
, reverse the nodes of the list from positionleft
to positionright
, and returnthe 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
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode() {} * ListNode(int val) { this.val = val; } * ListNode(int val, ListNode next) { this.val = val; this.next = next; } * }*/ class Solution { public ListNode reverseBetween(ListNode head, int l, int r) { ListNode pre = new ListNode(0); pre.next = head; ListNode leftpre = pre,rightpre=pre; //leftpre指向left的前一個 for(int i=1;i<l;i++) leftpre=leftpre.next; //rightpre指向right當前,記住這裡是當前,不是前一個!for(int i=1;i<=r;i++) rightpre=rightpre.next; //left指向要反轉的第一個node ListNode left=leftpre.next; //right指向第一個不反轉的node ListNode right = rightpre.next; //防止死迴圈 rightpre.next=null; //反轉前的第一個為反轉後的最後一個 ListNode lefttail = left; //進行反轉,並將反轉結果對接leftpre leftpre.next = reverse(left); //對接反轉自後一個與未反轉部分 lefttail.next=right; return pre.next; } //簡單的連結串列反轉過程 public ListNode reverse(ListNode head){ ListNode pre = new ListNode(0); while(head!=null){ ListNode temp=pre.next; pre.next=head; head=head.next; pre.next.next=temp; } return pre.next; } }