Leetcode 92. Reverse Linked List II

思路:添加頭節點,反轉鏈表某個連續部分,206. Reverse Linked List是本題的特殊狀況,也能夠像本題同樣作,具體見Leetcode 206. Reverse Linked Listhtml

 1 /**
 2  * Definition for singly-linked list.
 3  * public class ListNode {
 4  *     int val;
 5  *     ListNode next;
 6  *     ListNode(int x) { val = x; }
 7  * }
 8  */
 9 class Solution {
10     public ListNode reverseBetween(ListNode head, int m, int n) {
11         if(head == null) return head;
12         ListNode dummy = new ListNode(0);
13         dummy.next = head;
14         ListNode pre = dummy;
15         for(int i = 0; i < m - 1; i++) pre = pre.next;//移動m-1次
16         ListNode start = pre.next;
17         ListNode then = start.next;
18         for(int i = 0; i < n - m; i++) {//須要將start後面的n-m個點陸續反轉
19             start.next = then.next;//start的後面指向then的後面
20             then.next = pre.next;//then的後面指向pre的後面,至關於將then插入pre和pre.next之間
21             pre.next = then;//pre的後面是then
22             then = start.next;//完成一個元素的反轉後,then指向下一個準備被反轉(插入pre和pre.next之間)的節點
23         }
24         return dummy.next;
25     }
26 }

 

Next challenges: Swap Nodes in Pairs Remove Duplicates from Sorted List II Delete Node in a Linked Listnode

Next challenges: Reverse Nodes in k-Group Linked List Cycle II Intersection of Two Linked Listsspa

相關文章
相關標籤/搜索