LeetCode - Rotate List
2013-08-24 17:32
288 查看
Given a list, rotate the list to the right by k places, where k is
non-negative.
For example:
Given
return
non-negative.
For example:
Given
1->2->3->4->5->NULLand k =
2,
return
4->5->1->2->3->NULL.
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: int getSize(ListNode *head){ ListNode *p=head; int counter=0; while(p){ p=p->next; counter++; } return counter; } ListNode *rotateRight(ListNode *head, int k) { if(k<=0||head==NULL){ return head; } k%=getSize(head);//注意这里,k的大小可能超过链表长度 if(k==0){ return head; } ListNode *p=head, *q=head, *r; int counter=0; while(q&&counter<k){//循环直到q指向正数第k+1个结点 q=q->next; counter++; } while(q->next){//循环直到q指向最后一个结点时,p正好指向倒数第k+1个结点 p=p->next; q=q->next; } q=p->next; p->next=NULL; p=q;//p、q分别指向需要提前的结点的首、尾结点 while(q->next){ q=q->next; } q->next=head; head=p; return head; } };
相关文章推荐
- LeetCode:Rotate List(旋转链表)
- [leetcode]Rotate List
- LEETCODE: Rotate List
- LeetCode 61 - Rotate List
- LeetCode Rotate List
- [LeetCode] 61. Rotate List
- LeetCode-61-Rotate List 链表水题
- LeetCode_61---Rotate List
- [leetcode-61]Rotate List(c)
- LeetCode 61. Rotate List
- 【leetcode】Rotate List
- 061 Rotate List [Leetcode]
- leetcode - Rotate List
- LeetCode -- Rotate List
- LeetCode||61. Rotate List
- [LeetCode]Rotate List
- LeetCode 61: Rotate List
- Leetcode 61. Rotate List
- C++ STL@ list 应用 (leetcode: Rotate Array)
- leetcode61~Rotate List