LeetCode 61. Rotate List(循环右移单链表)
程序员文章站
2022-03-22 13:12:08
...
题目描述:
Given a list, rotate the list to the right by k places, where k is non-negative.
例子:
Given 1->2->3->4->5->NULL and k = 2, return 4->5->1->2->3->NULL.
分析:
题意:给定一个单链表,返回将它循环右移k(k是非负整型数)次的结果。
时间复杂度为O(n)。
代码:
#include <bits/stdc++.h>
using namespace std;
struct ListNode{
int val;
ListNode *next;
ListNode(int x): val(x), next(NULL){}
};
class Solution {
public:
ListNode* rotateRight(ListNode* head, int k) {
// Exceptional Case:
if(!head || !head->next || k == 0){
return head;
}
// cnt
int n = 0;
ListNode *pre = head, *p = head, *q = head;
while(p){
n++;
p = p->next;
}
k = k % n;
// check important!
if(k == 0){
return head;
}
for(int i = 1; i <= k; i++){
q = q->next;
}
while(q->next){
pre = pre->next;
q = q->next;
}
p = pre->next;
pre->next = NULL;
q->next = head;
return p;
}
};
上一篇: 洛谷P3919可持久化线段树
下一篇: Maven环境搭建(学习笔记记录)