Rotate List leetcode java


題目:

 

Given a list, rotate the list to the right by k places, where k is non-negative.

For example:
Given 1->2->3->4->5->NULL and k = 2,
return 4->5->1->2->3->NULL.

 

題解:

這道題主要先理解題意,就是倒着數k個node,從那開始到結尾和之前那部分對調,那個例子就是,4->5拿前面來,1->2->3拿后面去。

幾個特殊:

k是可以大於整個list的長度的,所以這時要對k對len取模

如果取模之后得0,相當於不用rotate,直接返回

 

處理完特殊情況后,就用熟悉的faster/slower雙指針解決就好(看到這種linkedlist,倒着數數的,就條件反射了)

先對faster設步長為n,然后faster和slower再一起走,知道faster.next==null,說明slower指向要倒着數的開始點的前一個位置。

所以slow.next就是要返回的newhead,保存一下。

然后把faster.next接到head上,slower.next存為null,作隊尾。

這樣就把list給rotate了。

這是我想的一種解法,還有一種就是把整個list連起來,變成環,找到切分點斷開就行。

 

解法1:

 

 1     public ListNode rotateRight(ListNode head,  int n) {
 2          if(head== null||head.next== null||n==0)
 3              return head;
 4         ListNode fast = head, slow = head,countlen = head;
 5         ListNode newhead =  new ListNode(-1);
 6          int len = 0;
 7         
 8          while(countlen!= null){
 9             len++;
10             countlen = countlen.next;
11         }
12         
13         n = n%len;
14          if(n==0)
15              return head;
16         
17          for( int i = 0; i < n; i++)
18             fast = fast.next;
19         
20          while(fast.next!= null){
21             slow = slow.next;
22             fast = fast.next;
23         }
24         
25         newhead = slow.next;
26         fast.next = head;
27         slow.next =  null;
28         
29          return newhead;
30     }

解法2:

 1  public ListNode rotateRight(ListNode head,  int n) {
 2 
 3      if (head ==  null || n == 0)
 4          return head;
 5     ListNode p = head;
 6      int len = 1; // since p is already point to head
 7       while (p.next !=  null) {
 8         len++;
 9         p = p.next;
10     }
11     p.next = head;  // form a loop
12      n = n % len;
13      for ( int i = 0; i < len - n; i++) { 
14         p = p.next;
15     }  // now p points to the prev of the new head
16      head = p.next;
17     p.next =  null;
18      return head;
19 }

 Reference for 2: http://leetcodenotes.wordpress.com/2013/08/14/leetcode-rotate-list-%E6%8A%8A%E5%90%8Ek%E4%B8%AArotate%E5%88%B0list%E5%89%8D%E9%9D%A2%E5%8E%BB%EF%BC%8Ck%E5%8F%AF%E4%BB%A5%E8%B6%85%E8%BF%87list%E6%9C%AC%E8%BA%AB%E9%95%BF%E5%BA%A6/


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM