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點的節點為軸,旋轉這個鏈表,k為非負數。
比如:
Given 1->2->3->4->5->NULL and k = 2,
return 4->5->1->2->3->NULL.
* 給出一個單鏈表,和一個K值,根據K值往右旋轉,例如:
* 注意審題 ,開始以為K點從左邊開始呢,debug費了那麼大勁~~
* K是從右向左數的
*還需要特別說明的一點是,k的值可能會超過鏈表中的節點數,這時候需要對k進行取余操作,重新定位k在鏈表中的位置。當k取余數0時,說明為總節點數的
*整數倍,這時候依照題意鏈表不需要進行翻轉。
* [1,2,3,4,5] k=1 ----->[5,1,2,3,4]
* [1,2,3,4,5] k=2 ----->[4,5,1,2,3]
* [1,2,3,4,5] k=3 ----->[3,4,5,1,2]
* [1,2,3,4,5] k=4 ----->[2,3,4,5,1]
參考http://pisxw.com/algorithm/Rotate-List.html
此題解法依舊是利用雙指針,基本思路是設置兩個指針i,j,中間相差n,用walker-runner定位到要旋轉的那個結點,然後將下一個結點設為新表頭,並且把當前結點設為表尾。設置前後兩個指針,然後推進前進的方法稱為尺取法。
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution
{
public ListNode rotateRight(ListNode head, int n)
{
if(head==null || head.next==null)
return head;
ListNode slow=head; //定義兩個指針
ListNode fast=head;
ListNode testhead =head;//復制鏈表,用於後面統計鏈表中的總的節點數
int Nodenum=0; //鏈表中的節點數
int k;
while(testhead!=null)
{
Nodenum++; //統計總共多少節點
testhead=testhead.next;
}
k=n%Nodenum;
if(k==0) //若n正好為節點數的整數倍,就不用翻轉鏈表
return head;
for(int num=0;num
自己第一遍的AC代碼,真叫一個亂啊,捨不得還是記錄下吧
public class Solution
{
public ListNode rotateRight(ListNode head, int k)
{
//1->2->3->4->5->NULL
//4->5->1->2->3->NULL.
int Nodenum=0;
ListNode testhead2;
ListNode testhead3;
ListNode newListone;
ListNode newListtwo;
ListNode Listtwoend;
if(head==null||head.next==null)
return head;
ListNode testhead =head;
while(testhead!=null)
{
Nodenum++;
testhead=testhead.next;
}
k=k%Nodenum;
if(k>=Nodenum||k==0)
return head;
testhead2=head;
testhead3=head;
for(int i=1;i