61.Rotate List¶
Tags: Medium
Link List
Link: https://leetcode.com/problems/rotate-list/
Given a linked list, rotate the list to the right by k places, where k is non-negative.
Example 1:
Input: 1->2->3->4->5->NULL, k = 2
Output: 4->5->1->2->3->NULL
Explanation:
rotate 1 steps to the right: 5->1->2->3->4->NULL
rotate 2 steps to the right: 4->5->1->2->3->NULL
Example 2:
Input: 0->1->2->NULL, k = 4
Output: 2->0->1->NULL
Explanation:
rotate 1 steps to the right: 2->0->1->NULL
rotate 2 steps to the right: 1->2->0->NULL
rotate 3 steps to the right: 0->1->2->NULL
rotate 4 steps to the right: 2->0->1->NULL
Answer:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* rotateRight(ListNode* head, int k) {
ListNode *dummy = new ListNode(-1);
dummy -> next = head;
ListNode *cur, *pre;
pre = dummy;
int num=0; //用来统计链表元素个数
while(pre -> next) {++num; pre = pre -> next;}
if(num == 0 || num == 1) return head;
for(int i = 0; i < k % num; ++i)
{
pre = dummy;
cur = pre -> next;
while(cur -> next) {cur = cur -> next;pre = pre -> next;}
cur -> next = dummy -> next;
pre -> next = NULL;
dummy -> next = cur;
}
return dummy -> next;
}
};
此种方法速度最快:Runtime: 8 ms, faster than 100.00% of C++ online submissions for Rotate List.Memory Usage: 8.9 MB, less than 100.00% of C++ online submissions for Rotate List.
Answer2:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* rotateRight(ListNode* head, int k) {
if(!head || k == 0) return head;
ListNode *p = head;
int len=1;
while(p -> next) //求链表的长度
{
++len;
p = p -> next;
}
k = len - k % len;
p -> next = head; //首尾相连
for(int step = 0; step < k; ++step)
{
p = p -> next;
}
head = p -> next; //新的首节点
p -> next = NULL; //断开环
return head;
}
};
此种方法是先首尾相连形成一个环,最后断开环,速度一般:Runtime: 16 ms, faster than 40.50% of C++ online submissions for Rotate List.