您的位置:首页 > 编程语言 > C语言/C++

[LeetCode] Rotate List

2015-06-18 14:41 363 查看


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
.
解题思路:

这道题题意说得不大明白。因此让我NG了好多遍。

这里的k是指右边的节点数目,如题,k指的是4和5。

另外一个题目没有说明白的就是,若k大于链表长度该如何处理。经过多次NG,发现是将k%len。

明白这些,编码就很容易了。面试的时候一定要问清楚面试官。

/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* rotateRight(ListNode* head, int k) {
int len = getListLen(head);
if(k<=0 || len==0){
return head;
}
k = k%len;
ListNode* myHead = new ListNode(0);
ListNode* tail = myHead;
ListNode* p = head;
for(int i=len-k;i>0;i--){
tail->next = p;
tail=tail->next;
p=p->next;
}
tail->next = NULL;
tail = myHead;
ListNode* q;
while(p!=NULL){
q=p->next;
p->next = tail->next;
tail->next=p;
tail=tail->next;
p=q;
}
head=myHead->next;
delete myHead;
return head;
}
int getListLen(ListNode* head){
int len = 0;
while(head!=NULL){
head=head->next;
len++;
}
return len;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  c++ leetcode