Rotate List

来源:互联网 发布:go python 编辑:程序博客网 时间:2024/06/08 04:22

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.

比较简单,记下原始链表的头、尾、分割点,然后2部分重新连接下就行。

注意K可能比总长度大,所以移动k%length

ListNode *rotateRight(ListNode *head, int k){    if (head == NULL || head->next == NULL || k == 0)        return head;    int length = 0;    ListNode *p = head, *old_tail = head;    while (p != NULL)    {        length++;        old_tail = p;        p = p->next;    }    k %= length;    ListNode *new_tail = head, *new_head = head;    for (int i = 0; i < length - k - 1; i++)    {        new_tail = new_tail-> next;    }    old_tail->next = head;    new_head = new_tail->next;    new_tail->next = NULL;    return new_head;}


0 0