1. 程式人生 > >Leetcode 92. 反轉鏈表 II

Leetcode 92. 反轉鏈表 II

click gif tno 兩個 分享圖片 bdc emp else nod

反轉從位置 mn 的鏈表。請使用一趟掃描完成反轉。

說明:
1 ≤ mn ≤ 鏈表長度。

示例:

輸入: 1->2->3->4->5->NULL, m = 2, n = 4
輸出: 1->4->3->2->5->NULL

思路:分成兩個情況來寫
第一種:如果m=1,那就是一道反轉鏈表,先翻轉m-n的節點,翻轉後,頭結點就變成了尾節點,所以把這些節點保存起來,然後再把後面的節點接到尾節點
第二種:如果!=1,翻轉m到n的中間節點即可
技術分享圖片
 1 public class 反轉鏈表II {
 2
ListNode reverseBetween(ListNode head, int m, int n) { 3 if(head==null||head.next==null) 4 return head; 5 6 if(m!=1) 7 { 8 ListNode first=head;//記錄翻轉處的前一個節點 9 ListNode temp=head.next;//記錄尾節點 10 for(int i=0;i<m-2;i++)
11 { 12 temp=temp.next; 13 first=first.next; 14 } 15 ListNode la=temp; 16 ListNode pre=temp;//反轉的起始節點 17 ListNode p=temp.next; 18 ListNode next=null; 19 for(int i=0;i<n-m;i++)
20 { 21 next=p.next; 22 p.next=pre; 23 pre=p; 24 p=next; 25 } 26 first.next=pre; 27 la.next=p; 28 29 } 30 else { 31 ListNode pre=head; 32 ListNode la=pre; 33 ListNode p=head.next; 34 ListNode next=null; 35 36 for(int i=0;i<n-m;i++) 37 { 38 next=p.next; 39 p.next=pre; 40 pre=p; 41 p=next; 42 } 43 la.next=p; 44 return pre;//反轉後的頭結點 45 46 } 47 48 return head; 49 } 50 public static void main(String argc[]) 51 { 52 53 } 54 }
View Code

Leetcode 92. 反轉鏈表 II