您的位置:首页 > 其它

[LeetCode]Rotate List

2015-08-19 18:14 316 查看

题目

Number: 61

Difficulty: Medium

Tags: Linked List, Two Pointers

Given a list, rotate the list to the right by k places, where k is non-negative.

For example:

[code]Given 1->2->3->4->5->NULL and k = 2,
return 4->5->1->2->3->NULL.


题解

反转倒数第k个结点开头的链表。

代码

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