61-Rotate List

来源:互联网 发布:李乐的霍去病 知乎 编辑:程序博客网 时间:2024/06/07 00:38
题目

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.

分析

方法的思路是遍历一遍找到尾结点,并记录链表长度,然后连接成一个环,再遍历一遍找到第n-k个结点,并把链表从中间断开。

实现
class Solution {public:    ListNode* rotateRight(ListNode* head, int k) {        if (head == NULL || head->next == NULL || k == 0)            return head;        int len = 1;        ListNode *tail = head;        while (tail->next)        {            tail = tail->next;            len++;        }        tail->next = head;        k = k%len;        for (int i = 0; i < len - k; i++)            tail = tail->next;        head = tail->next;        tail->next = NULL;        return head;    }};
原创粉丝点击