1. 程式人生 > >【Leetcode】61. Rotate List

【Leetcode】61. Rotate List

int main 結點 struct urn 新的 tno pre 實例

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

Example:

Given 1->2->3->4->5->NULL and k = 2,

return 4->5->1->2->3->NULL.

Tips:右移結點,過程如下:

k=2,右移兩次:

①5->1->2->3->4

②4->5->1->2->3

思路:(1)實例化一個fast指針,使其等於head結點,使fast指針先向後移動k次。

(2)創建一個slow指針,然後兩個指針一起向後移動,直到fast.next!=null,停止。

(3)k的值可能大於鏈表總長度,需要對k取余,k = k%count;

(4)使fast.next等於head,slow的下一個結點作為新的頭結點。

package medium;

import dataStructure.ListNode;

public class L61RotateList {
    /*
     * Given a list, rotate the list to the right by k places, where k is
     * non-negative.
     * 
     * Example:
     * 
     * Given 1->2->3->4->5->NULL and k = 2,
     * 
     * return 4->5->1->2->3->NULL.
     * 
     
*/ public ListNode rotateRight(ListNode head, int k) { if(head==null || k<0)return null; ListNode node = new ListNode(0); node.next = head; ListNode fast=head; ListNode newHead=head; int count=0; while(newHead!=null){ count++; newHead
=newHead.next; } if(k > count) k = k%count; for(int i=0;i<k;i++){ fast=fast.next; } if(fast==null){ return node.next; }else{ ListNode slow=head; while(fast.next!=null){ slow=slow.next; fast=fast.next; } fast.next=head; ListNode cur=slow.next; node.next=cur; slow.next=null; } return node.next; } public static void main(String[] args) { ListNode head1 = new ListNode(1); ListNode head2 = new ListNode(2); ListNode head3 = new ListNode(3); ListNode head4 = new ListNode(4); ListNode head5 = new ListNode(5); ListNode head6 = null; head1.next = head2; head2.next = head3; head3.next = head4; head4.next = head5; head5.next = head6; L61RotateList l61=new L61RotateList(); int k=2; ListNode node=l61.rotateRight(head1, k); while(node!=null){ System.out.println(node.val); node=node.next; } System.out.println("~~~~~~~~~~~~~~~~~~~~~~~~"); ListNode h1 = new ListNode(1); ListNode h2=new ListNode(2); h1.next=h2; h2.next=null; ListNode node1=l61.rotateRight(h1, 3); while(node1!=null){ System.out.println(node1.val); node1=node1.next; } } }

【Leetcode】61. Rotate List