Leetcode: Reverse Linked List II

來源:互聯網
上載者:User

標籤:style   class   blog   code   ext   color   

Reverse a linked list from position m to n. Do it in-place and in one-pass.For example:Given 1->2->3->4->5->NULL, m = 2 and n = 4,return 1->4->3->2->5->NULL.Note:Given m, n satisfy the following condition:1 ≤ m ≤ n ≤ length of list.

Analysis: 這道題還是想了我蠻久,先是題意理解錯了,以為只是m和n這兩個位置對調,結果發現其實是m到n之間的所有元素都需要調換。一時之間沒有想到怎樣做reverse比較好,參考了一下網上的思路,發現這樣做比較好:還是要用Runner Technique,還是要用Dummy Node;兩個指標: npointer指到n的位置,mpointer指到m的前一位;每一次把mpointer後一位的元素放到npointer的後一位:mpointer.next.next = npointer.next;直到mpointer.next = npointer為止(m與n重合)

Original linked list:       1->2->3->4->5->6->7; m = 3, n =6

Step1:        1->2->4->5->6->3->7    

Step2:      1->2->5->6->4->3->7           

......

Result:      1->2->6->5->4->3->7

Note that pointer m is switching to right one by one in each step, but pointer n remains no change.

再次體現了在鏈表題中使用Dummy Node, 並且對當前node.next進行操作的好處。

 

Notice: 像這種鏈表刪除插入操作,在刪除插入之前,最好先拷貝一下被刪除節點的下一個節點,以及插入位置的下一個節點,把它們存在一個變數ListNode store裡面,直接去訪問這個變數,而不要用類似mpointer.next的方式存著他們,因為這樣受制於mpointer,mpointer一旦變化,就找不到這些刪除/插入節點的下一個節點了。

 1 /** 2  * Definition for singly-linked list. 3  * public class ListNode { 4  *     int val; 5  *     ListNode next; 6  *     ListNode(int x) { 7  *         val = x; 8  *         next = null; 9  *     }10  * }11  */12 public class Solution {13     public ListNode reverseBetween(ListNode head, int m, int n) {14         ListNode prev = new ListNode(-1);15         prev.next = head;16         ListNode mpointer = prev; //point to m-1 position17         ListNode npointer = prev; //point to n position18         while (m > 1) {19             mpointer = mpointer.next;20             m--;21         }22         while (n > 0) {23             npointer = npointer.next;24             n--;25         }26         while (mpointer.next != npointer) {27             ListNode mnext = mpointer.next.next;28             ListNode nnext = npointer.next;29             mpointer.next.next = nnext;30             npointer.next = mpointer.next;31             mpointer.next = mnext;32         }33         return prev.next;34     }35 }

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.