[面试真题] LeetCode: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.

解法:游标指针从头节点向后移动,当指向尾节点时,得到链表长度len,同时将链表头尾相连,接着游标再向后移动 k % len 步得到结果链表的尾节点。

 1 /**
 2  * Definition for singly-linked list.
 3  * struct ListNode {
 4  *     int val;
 5  *     ListNode *next;
 6  *     ListNode(int x) : val(x), next(NULL) {}
 7  * };
 8  */
 9 class Solution {
10 public:
11     ListNode *rotateRight(ListNode *head, int k) {
12         // Start typing your C/C++ solution below
13         // DO NOT write int main() function
14         if(head){
15             int len = 1;
16             ListNode *p = head;
17             while(p->next){
18             p = p->next;
19             len++;
20             }
21             p->next = head;
22             k %= len;
23             int step = len - k;
24             while(step>0){
25                 p = p->next;
26                 step--;
27             }
28             head = p->next;
29             p->next = NULL;
30         }
31         return head;
32     }
33 };

Run Status: Accepted!
Program Runtime: 56 milli secs

Progress: 229/229 test cases passed.
posted @ 2013-05-14 10:38  infinityu  阅读(770)  评论(0编辑  收藏  举报