首页 > 代码库 > 【LeetCode】Rotate List
【LeetCode】Rotate List
Rotate List
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
.
思路如下:将链表首尾相连成环。寻找尾节点的同时可以计算链表长度。
记链表长度为size,则移位次数为r=k%size。
也就是说链表的后r个节点成为新链表的前半部分,链表的前size-r个节点为新链表的后半部分。
因此head往右第size-r-1个节点为新链表的尾节点newtail,head往右第size-r个节点为新链表的头节点newhead。
将newtail->next,返回newhead即可。
由于我们在计算size时已经将原链表首尾相连,因此不存在断点。
/** * 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 == NULL || head->next == NULL) return head; else { int size = 1; ListNode* tail = head; while(tail->next) { size ++; tail = tail->next; } //tail point to the last node int r = k%size; if(r == 0) return head; else { tail->next = head; int shift = size-r-1; while(shift--) head = head->next; //head is new tail ListNode* newhead = head->next; head->next = NULL; return newhead; } } }};
【LeetCode】Rotate List
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。