Rotate List -- leetcode

来源:互联网 发布:美科网络 编辑:程序博客网 时间:2024/06/16 03:26

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;    }};


0 0
原创粉丝点击