LeetCode

来源:互联网 发布:网页设计程序员工资 编辑:程序博客网 时间:2024/05/29 18:30

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.

一个链表的,重新衔接。

最开始一直TLE,我还十分纳闷,不可能发生死循环啊。然后发现链表头尾衔接后不是代码死循环,是输出死循环了orzzzzzzz

思路就是将链表形成环,然后在合适的地方断开(然额最开始我天真地以为我只是增加了长度。。)时间复杂度O(n),空间复杂度O(1)

/** * 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) return head;                int cnt = 1;        ListNode* cur = head;        ListNode* ans = head;        while (cur->next) {            cnt++;            cur = cur->next;        }        cur->next = head;                if (k %= cnt) {            for (int i = 0; i < cnt - k; ++i)                 cur = cur->next;        }        ans = cur->next;        cur->next = NULL;   //断开!!!断开!!!        return ans;    }};