#include <iostream>
#include <stdio.h>
#include <vector>
using namespace std;
/*
问题:
Given a list, rotate the list to the right by k places, where k is non-negative.
For example:
Given 1->2->3->4->5->NULL and k = 2,
return 4->5->1->2->3->NULL.
分析:题目的意思应该是将链表最右侧的结点转转到最左边,重复这样的操作k次。此题可以等效替换成寻找到倒数第k个结点,
断开倒数第k+1个结点与倒数第k个结点的连接,并使得倒数第k+1个结点指向NULL,然后将尾结点
(不含NULL)指向头结点
那么问题关键变成寻找倒数第k+1个结点和尾结点,问题就解决了。
寻找倒数第k+1个结点,等于寻找正数第n-k,设链表长度为n。设置快慢指针
当快指针到达n+1(即空指针)时,慢指针到达n-k
n, n-k-1
...
k+3 2
k+2 , 1
所以快指针先走k+1步,然后一起走
//但是这里必须确保k必须小于链表长度
输入:
7(链表长度) 2(k)
1 2 3 4 5 6 7
1 1
1
7 5
1 2 3 4 5 6 7
7 6
1 2 3 4 5 6 7
输出:
6 7 1 2 3 4 5
1
3 4 5 6 7 1 2
2 3 4 5 6 7 1
关键:
1 那么问题关键变成寻找倒数第k+1个结点和尾结点,问题就解决了。
寻找倒数第k+1个结点,等于寻找正数第n-k,设链表长度为n。设置快慢指针
当快指针到达n+1(即空指针)时,慢指针到达n-k
n, n-k-1
...
k+3 2
k+2 , 1
所以快指针先走k+1步,然后一起走
推演倒数第k个结点需要快指针为n+1,慢指针为对应值的推演,因为循环条件是快指针退出
*/
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
class Solution {
public:
ListNode* rotateRight(ListNode* head, int k) {
if(NULL == head || k <= 0)
{
return head;
}
//计算链表长度,并寻找链表尾部
int listLen = 0;
ListNode* previousNode = NULL;
ListNode* node = head;
while(node)
{
listLen++;
previousNode = node;
node = node->next;
}
//令k = k % listLen
if(listLen == 0)
{
return head;
}
k %= listLen;
//链表长度倍数,无需反转
if(k == 0)
{
return head;
}
ListNode* fast = head;
//快指针先走k+1步,确保慢指针为2的时候,快指针为k+3
for(int i = 0 ; i <= k ; i++)
{
fast = fast->next;
}
//一起走
ListNode* slow = head;
while(fast)
{
fast = fast->next;
slow = slow->next;
}
ListNode* newHead = slow->next;
slow->next = NULL;
previousNode->next = head;
return newHead;
}
};
void print(ListNode* head)
{
if(NULL == head)
{
cout << "no result" << endl;
return;
}
ListNode* node = head;
while(node)
{
cout << node->val << " ";
node = node->next;
}
cout << endl;
}
//构建链表
ListNode* buildList(vector<int>& nums)
{
if(nums.empty())
{
return NULL;
}
ListNode* head;
ListNode* tail;
//采用尾插法构建链表
int size = nums.size();
for(int i = 0 ; i < size ; i++)
{
if(i)
{
ListNode* node = new ListNode(nums.at(i));
tail->next = node;
tail = node;
}
else
{
head = new ListNode(nums.at(i));
tail = head;
}
}
return head;
}
void deleteList(ListNode* head)
{
ListNode* node;
while(head)
{
node = head->next;
delete head;
head = node;
}
}
void process()
{
vector<int> nums;
int value;
int num;
Solution solution;
vector<int> result;
int k;
while(cin >> num >> k )
{
nums.clear();
for(int i = 0 ; i < num ; i++)
{
cin >> value;
nums.push_back(value);
}
ListNode* head = buildList(nums);
ListNode* newHead = solution.rotateRight(head , k);
print(newHead);
deleteList(newHead);
}
}
int main(int argc , char* argv[])
{
process();
getchar();
return 0;
}
leecode 解题总结:61. Rotate List
最新推荐文章于 2023-03-20 08:17:47 发布