题目:输入k和链表的头结点,循环右移链表的后K个结点。
For example:
Given1->2->3->4->5->NULLand k =2,
return4->5->1->2->3->NULL.
思路:
1.首先要找链表的倒数第K个结点;
2.因循环右移的K个结点仍是按原来顺序排列,可考虑用一个先进先出的容器即队列将后K个结点
存储,依次连接在链表首处;
3.但此解法空间复杂度为O(k);
4.将链表首尾相接成环,然后在第K个结点前的结点处断开即可;
因leetcode上测试用例中的k有大于length of list 的情况,故要先遍历一遍然后使k=k%(length of list),
时间复杂度仍为O(n).
代码如下:
/**
* 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;
//测试用例中有n大于length of list的情况;
ListNode temp=head;
int count =1;
while(temp.next!=null)
{
temp=temp.next;
count++;
}
n=n%count;
if(0 == n)
return head;
ListNode first=head;
ListNode second=head;
//先找到倒数第n个结点;
int num=1;
while(num<n&&second!=null)
{
second=second.next;
num++;//while循环中一定要注意别少了对变量的修改,避免进入死循环;
}
//firstpre记录倒数第n个结点的上一个结点;
ListNode firstpre=first;
while(second.next!=null)
{
firstpre=first;
first=first.next;
second=second.next;
}
second.next=head;
head=first;
firstpre.next=null;
return head;
}
}