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.
解题思路:
1、先遍历整个链表求出总长度length
2、根据k求出链表的新的head在什么位置,length-k的位置
3、假如p指向length-k-1的地方,head=p.next,然后将p.next=null,因为它要作为链表的结尾
3、然后从新的head节点遍历到末尾,链接到初始head节点的位置。
出错的地方:题目中k的值可以大于链表的长度。那要怎么解决呢?实际上当k值大于链表长度时,旋转k次的结果等于k%length后的结果。我们在这稍加判断即可。
if (head == null)
return null;
int length=1;
int i = 1;
ListNode p = head;
ListNode q = head;
while(p.next!=null)
{
p=p.next;
length++;
}
p=head;
if(n>length)n=(n%length);
int k=length-n;
if(k==0)return head;
while (p.next != null)
{
if (i > k-1)
break;
p = p.next;
i++;
}
if (p.next != null)
{
head = p.next;
p.next = null;
}
else
return head;
p = head;
while (p.next != null)
p = p.next;
p.next = q;
return head;

本文介绍了一种链表右旋算法的实现思路,通过遍历链表获取长度,并找到新的头部节点位置,调整指针连接形成正确的链表结构。特别讨论了当旋转次数大于链表长度的情况。
571

被折叠的 条评论
为什么被折叠?



