/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
/*1.先遍历一遍链表找到链表的尾结点,计算链表的长度。
2.将链表的尾结点与头结点相连。
3.遍历链表找到需要断开的结点,将它们断开并返回头结点指针。
参考自:https://github.com/soulmachine/leetcode*/
class Solution {
public:
ListNode *rotateRight(ListNode *head, int k) {
ListNode newHead(-1);
newHead.next = head;
int count(0);
//计算链表长度
ListNode *tail = &newHead;
for(ListNode *cur = head;cur != nullptr; tail = tail->next, cur = cur->next) ++count;
if(count == 0) return head;
int num = k % count;
//首尾相连
tail->next = head;
ListNode *cur = &newHead;
for(int i = 0; i < count - num; ++i) cur = cur->next;
head = cur->next;
cur->next = nullptr;
return head;
}
};
LeetCode之Rotate List
最新推荐文章于 2021-02-22 00:22:50 发布