LeetCode進階之路(Rotate List)
阿新 • • 發佈:2019-01-24
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位置,第一位,然後把三段拼起來。思路是正確,但是太複雜,繞來繞去,後面提交也是超時了。
public ListNode rotateRight(ListNode head, int k) { ListNode result = new ListNode(-1); result.next = head; ListNode first = result; ListNode second = head; ListNode third = result; if(head == null) { return result.next; } if(head.next == null){ return head; } int len = 1; while(result.next != null) { len++; result = result.next; } int i = 0; while(i < len-k) { i++; first = first.next; } third.next = first; int j = 1; while(j < len-1-k) { second = second.next; j++; } second.next = null; ListNode flag = third; while(flag.next != null) { flag = flag.next; } flag.next = head; return third.next; }
下面是參考網友的思路,用兩個指標,faster/slower,先對faster設步長為n,然後faster和slower再一起走,知道faster.next==null,說明slower指向要倒著數的開始點的前一個位置。
還有一種更簡單的思路,把整個連結串列連成一個環,在重新分割就可以了。public ListNode rotateRight(ListNode head, int n) { if(head==null||head.next==null||n==0) return head; ListNode fast = head, slow = head,countlen = head; ListNode newhead = new ListNode(-1); int len = 0; while(countlen!=null){ len++; countlen = countlen.next; } n = n%len; if(n==0) return head; for(int i = 0; i < n; i++) fast = fast.next; while(fast.next!=null){ slow = slow.next; fast = fast.next; } newhead = slow.next; fast.next = head; slow.next = null; return newhead; }
public ListNode rotateRight(ListNode head, int n) {
if (head == null || n == 0)
return head;
ListNode p = head;
int len = 1;//since p is already point to head
while (p.next != null) {
len++;
p = p.next;
}
p.next = head; //form a loop
n = n % len;
for (int i = 0; i < len - n; i++) {
p = p.next;
} //now p points to the prev of the new head
head = p.next;
p.next = null;
return head;
}