/**
* 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
最新推荐文章于 2024-10-08 11:15:15 发布
本文介绍了一种链表操作算法——旋转链表。该算法通过三次遍历实现:第一次遍历找到链表尾结点并计算长度;第二次遍历将尾结点与头结点相连;第三次遍历找到断开点,完成链表的旋转。
1189

被折叠的 条评论
为什么被折叠?



