提示:这个题目比较简单,只需要找到待断处的前一个节点就行,
题目描述:
给你一个链表的头节点 head
,旋转链表,将链表每个节点向右移动 k
个位置。
案例:
输入:head = [1,2,3,4,5], k = 2 输出:[4,5,1,2,3]
输入:head = [0,1,2], k = 4 输出:[2,0,1]
![](/i/l/?n=22&i=blog/1596343/202208/1596343-20220828160522603-827014710.png)
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode() : val(0), next(nullptr) {} * ListNode(int x) : val(x), next(nullptr) {} * ListNode(int x, ListNode *next) : val(x), next(next) {} * }; */ class Solution { public: ListNode* rotateRight(ListNode* head, int k) { if(head == NULL) { return NULL; } if(k == 0) { return head; } int len = 1; ListNode * end = head; while(end->next) { len++; end = end->next; } k = k % len; ListNode *p = head; ListNode *newHead = NULL; while(k--) { p = p->next; } end->next = head; newHead = p->next; p->next = NULL; return newHead; } };
标签:head,ListNode,int,next,链表,61,end,旋转 From: https://www.cnblogs.com/boost/p/16632959.html