Rotate List
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
.
最开始想直接用双指针做就行了。 但是发现n竟然可以比length长。
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 rotateRight(ListNode head, int n) { 14 // Note: The Solution object is instantiated only once and is reused by each test case. 15 ListNode fast = head; 16 ListNode cur = head; 17 if(n == 0) return head; 18 if(head == null)return null; 19 for(int i = 0; i < n; i ++){ 20 if(fast == null) return head; 21 fast = fast.next; 22 } 23 if(fast == null) return head; 24 while(fast.next != null){ 25 fast = fast.next; 26 cur = cur.next; 27 } 28 ListNode hd = cur.next; 29 cur.next = null; 30 fast.next = head; 31 return hd; 32 } 33 }
Solution:
首先从head开始跑,直到最后一个节点,这时可以得出链表长度len。然后将尾指针指向头指针,将整个圈连起来,接着往前跑len – k%len,从这里断开,就是要求的结果了。
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 rotateRight(ListNode head, int n) { 14 // Note: The Solution object is instantiated only once and is reused by each test case. 15 ListNode cur = head; 16 int len = 1; 17 if(head == null) return null; 18 while(cur.next != null){ 19 cur = cur.next; 20 len ++; 21 } 22 cur.next = head; 23 int t= len - n % len; 24 for(int i = 0; i < t; i ++){ 25 cur = cur.next; 26 } 27 ListNode hd = cur.next; 28 cur.next = null; 29 return hd; 30 } 31 }
posted on 2013-10-03 15:14 Step-BY-Step 阅读(229) 评论(0) 编辑 收藏 举报