标签:链表旋转 linkedlist rotate list
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
.
本文的题意就是循环将后面的n个结点移动到前面去,所以,n有可能是大于链表的长度的,这是一个小小的陷阱。然后就是很简单的细节了,有点脑残,提交了好多次。
public ListNode rotateRight(ListNode head, int n) { if(n<=0||head==null) return head; int len=1,index=0; ListNode pListNode=head,qListNode=null,tailListNode=null; while(pListNode.next!=null) { len++; pListNode=pListNode.next; } tailListNode=pListNode; n=n%len; if(n==0) return head; index=len-n; index--; pListNode=head; for(int i=0;i<index;i++) { pListNode=pListNode.next; } qListNode=pListNode.next; pListNode.next=null; pListNode=head; head=qListNode; tailListNode.next=pListNode; return head; }
标签:链表旋转 linkedlist rotate list
原文地址:http://blog.csdn.net/mnmlist/article/details/43371871