您的位置:首页 > 其它

Rotate List -- leetcode

2015-04-02 10:12 232 查看
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
.

在leetcode上实际执行时间为16ms。

基本思路:

1. 统计链表长度 count

2.首尾相接,做成循环链表。

3.从头再移动到第 count - k 结点,在此断开。

/**
 * 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) {
        if (!head || !head->next || !k) 
            return head;
        
        int count = 1;
        ListNode *p = head;
        while (p->next) {
            ++count;
            p = p->next;
        }
        
        p->next = head;
        
        k = k % count;
        k = count - k;
        while (k--)
            p = p->next;
            
        head = p->next;
        p->next = 0;
        return head;
    }
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: