旋转链表 使用vector压栈,倒着找到新的链表头,然后循环一把 - lifengyu360/lifengyu_first_git_test GitHub Wiki
给定一个链表,旋转链表,将链表每个节点向右移动 k 个位置,其中 k 是非负数。 /**
- 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 == nullptr
|| (k == 0)
|| (head->next == nullptr)) {
return head;
}
ListNode *tail = head;
int total = 1;
while (tail->next){
total++;
tail = tail->next;
}
tail->next = head;
k = k%total;
int num = total - k;//3
if (num == 0){
return head;
}
ListNode *tmp = head;
ListNode *tmp_pre = nullptr;
while (num > 0 ){
tmp_pre = tmp;
tmp = tmp->next;
num--;
}
tmp_pre->next = NULL;
return tmp;
}
};