1. 程式人生 > >LeetCode(61)-Rotate List

LeetCode(61)-Rotate List

61. Rotate List

Given a linked list, rotate the list to the right by k places, where k >
is non-negative.
Example 1:
Input: 1->2->3->4->5->NULL, k = 2
Output: 4->5->1->2->3->NULL
Explanation:
rotate 1 steps to the right: 5->1->2->3->4->NULL
rotate 2 steps to the right: 4->5->1->2->3->NULL
Example 2:
Input: 0->1->2->NULL, k = 4
Output: 2->0->1->NULL
Explanation:
rotate 1 steps to the right: 2->0->1->NULL
rotate 2 steps to the right: 1->2->0->NULL
rotate 3 steps to the right: 0->1->2->NULL
rotate 4 steps to the right: 2->0->1->NULL

嗯?這個題的意思是給一個連結串列,然後旋轉一下,怎麼旋轉呢?就是最後一個節點變為頭結點,其他的節點順序不變,放在頭結點的後面。然後引數k指的是旋轉的次數。
這個題不難,只是有個小小關鍵的地方,當選擇次數等於連結串列的長度的時候,連結串列又回到了最初的狀態,所以需要對引數k求餘,不然,等著超時吧。_

/**
 * Definition for singly-linked list.
 * public class ListNode {
     *     int val;
     *     ListNode next;
     *     ListNode(int x) { val = x; }
 * }
 */
class Solution { public ListNode rotateRight(ListNode head, int k) { if(head==null||null==head.next)return head; ListNode l=head; int j=1; while (null!=(l=l.next))j++; k=k%j; for (int i = 0; i <k; i++) { //最後一個節點 ListNode node=
null; //倒數第二個節點 ListNode node1 = null; //頭節點 ListNode h=head; while (null!=head.next){ node=head.next; node1=head; head=head.next; } node1.next=null; node.next=h; head=node; } return head; } }