LeetCode61Rotate List

来源:互联网 发布:sql安全性 编辑:程序博客网 时间:2024/06/04 00:28

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;}elsereturn head;p = head;while (p.next != null)p = p.next;p.next = q;return head;


0 0
原创粉丝点击