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

Leetcode 92.反轉鏈表

prev leetcode 說明 alt rev urn mil head style

92.反轉鏈表

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

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

示例:

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

輸出: 1->4->3->2->5->NULL

詳解見圖:

技術分享圖片

技術分享圖片

技術分享圖片

技術分享圖片

技術分享圖片

技術分享圖片

技術分享圖片

 1 public class Solution {
 2     public class ListNode {
 3         int val;
 4         ListNode next;
 5 
 6         ListNode(int
x) { 7 val = x; 8 } 9 } 10 11 public ListNode reverseBetween(ListNode head, int m, int n) { 12 if (head == null) { 13 return null; 14 } 15 ListNode dummy = new ListNode(0); 16 dummy.next = head; 17 ListNode prev = dummy;
18 for (int i = 0; i < m - 1; i++) { 19 prev = prev.next; 20 } 21 ListNode cur = prev.next; 22 ListNode post = cur.next; 23 for(int i=0;i<n-m;i++){ 24 cur.next=post.next; 25 post.next=prev.next; 26 prev.next=post;
27 post=cur.next; 28 } 29 return dummy.next; 30 } 31 }

Leetcode 92.反轉鏈表