LeetCode(Rotate List) 旋转链表

来源:互联网 发布:乌班图软件仓库 编辑:程序博客网 时间:2024/06/06 01:43

题目要求:

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.

思路: 首先求出链表的长度len, k = k % len,然后找到倒数第k个节点,添加一个虚拟头结点,然后将倒数第k节点到末尾节点用尾插法插入。


代码:

 ListNode *rotateRight(ListNode *head, int k)   {    if(head == NULL || k <=0)      return head;    int len = ListLength(head);    k = k % len;    if(k == 0)      return head;    ListNode* first = head, *second = head;    for(size_t i = 0; i < k; ++i)    {      first = first->next;    }    while(first->next != NULL)    {      first = first->next;      second = second->next;    }    ListNode* rotate_head = second->next;    second->next = NULL;    ListNode* virtual_head = new ListNode(0);    virtual_head->next = head;    ListNode* cur = virtual_head;    while(rotate_head != NULL)    {      ListNode* node = rotate_head->next;      rotate_head->next = cur->next;      cur->next = rotate_head;      rotate_head = node;      cur = cur->next;    }    ListNode* ret = virtual_head->next;    delete virtual_head;    virtual_head = NULL;    return ret;  }    int ListLength(ListNode* head)  {    if(head == NULL)      return 0;    int len = 0;    while(head != NULL)    {      ++len;      head = head->next;    }    return len;  }


0 0