题目大意:
给你一个链表,每 k 个节点一组进行翻转,请你返回翻转后的链表。
k 是一个正整数,它的值小于或等于链表的长度。
如果节点总数不是 k 的整数倍,那么请将最后剩余的节点保持原有顺序。
示例:
给你这个链表:1->2->3->4->5
当 k = 2 时,应当返回: 2->1->4->3->5
当 k = 3 时,应当返回: 3->2->1->4->5
说明:
你的算法只能使用常数的额外空间。
你不能只是单纯的改变节点内部的值,而是需要实际进行节点交换。
思路分析:
这题可以归结为翻转链表上的一段区间。
对于链表来说,可以进行这样的操作,如下图。
可能看起来它没有被反转,但是事实上它已经翻过来了!
当然你需要一个模式,来用循环实现。
p始终指向区间尾部。s始终指向区间的后一个,t为每次更新的链表节点。
解题代码:
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <algorithm>
#include <cmath>
#include <cstring>
#include <string>
#include <vector>
#include <queue>
#include <sstream>
#include <stack>
using namespace std;
struct ListNode
{
int val;
ListNode* next;
ListNode() : val(0), next(NULL) {}
ListNode(int x) : val(x), next(NULL) {}
ListNode(int x, ListNode* next) : val(x), next(next) {}
};
class Solution {
public:
ListNode* reverseBetween(ListNode* head, int m, int n)
{
ListNode* newHead = new ListNode(0);
newHead->next = head;
ListNode* p = newHead;
for (int i = 0; i < m - 1; i++)
p = p->next;
ListNode* start = p->next;
ListNode* tail = start->next;
for (int i = m; i < n; i++)
{
start->next = tail->next;
tail->next = p->next;
p->next = tail;
tail = start->next;
}
return newHead->next;
}
ListNode* reverseKGroup(ListNode* head, int k)
{
//填充本函数完成功能
ListNode* p, * p1, * p2;
if (k == 1)//边缘条件判断
return head;
ListNode* left, * right;
left = head;
p1 = head;
int x = 1, y = 0;
struct note {
int l, r;
}listChange[50000];
int number = 0;
while (p1 != NULL)
{
y++;
if (y % k == 0)
{
listChange[number].l = x;
listChange[number++].r = y;
x = y + 1;
}
p1 = p1->next;
}
for(int i=0;i<number;i++)
head = reverseBetween(head, listChange[i].l, listChange[i].r);
return head;
}
};
ListNode* createByTail()
{
ListNode* head;
ListNode* p1, * p2;
int n = 0, num;
int len;
cin >> len;
head = NULL;
while (n<len && cin >> num)
{
p1 = new ListNode(num);
n = n + 1;
if (n == 1)
head = p1;
else
p2->next = p1;
p2 = p1;
}
return head;
}
void displayLink(ListNode* head)
{
ListNode* p;
p = head;
cout << "head-->";
while (p != NULL)
{
cout << p->val << "-->";
p = p->next;
}
cout << "tail\n";
}
int main()
{
int k;
ListNode* head = createByTail();
cin >> k;
head = Solution().reverseKGroup(head, k);
displayLink(head);
return 0;
}