给定一个带头结点的单链表L,k
是一个正整数,它的值小于或等于链表的长度。如果节点总数不是 k
的整数倍,那么请将最后剩余的节点保持原有顺序。
你不能只是单纯的改变节点内部的值,而是需要实际进行节点交换。
示例
//库函数头文件包含
#include<iostream>
#include<stdio.h>
#include<stdlib.h>
using namespace std;
//函数状态码定义
#define TRUE 1
#define FALSE 0
#define OK 1
#define ERROR 0
#define INFEASIBLE -1
#define OVERFLOW -2
typedef int Status;
typedef int ElemType;
typedef struct LNode {
ElemType data;
struct LNode* next;
}LNode,*LinkList;
Status InitList(LinkList& L)
{
L = new LNode;
if (!L)exit(OVERFLOW);
L->next = NULL;
int n,t;
LNode* pre = L, * cur = NULL;
cin >> n;
for (int i = 0; i < n; i++)
{
cin >> t;
cur = new LNode;
if (!cur)exit(OVERFLOW);
cur->data = t;
cur->next = pre->next;
pre->next = cur;
pre = pre->next;
}
return OK;
}
void ListPrint(LinkList& L)
{
LNode* p = L->next;
while (p)
{
if (p->next)
cout << p->data << " ";
else
cout << p->data;
p = p->next;
}
cout << endl;
}
void MyReverse(LinkList& head, LinkList& tail)//实现子链的反转
{
LNode* prev = tail->next, *p = head;
while (prev != tail)
{
LNode* nex = p->next;
p->next = prev;
prev = p;
p = nex;
}
LNode* t = head; head = tail; tail = t; t = NULL;
}
void List_Part_Reverse(LinkList& L, int k)
{
LNode* pre = L,*one=L->next;
while (one)
{
LNode* tail = pre;
for (int i = 0; i < k; i++)//剩余是否够k个
{
tail = tail->next;
if (!tail)return;
}
LNode* nex = tail->next;
MyReverse(one, tail);
pre->next = one;
tail->next = nex;
pre = tail;
one = tail->next;
}
}
int main()
{
int k;
LinkList L;
InitList(L);
ListPrint(L);
cin >> k;
List_Part_Reverse(L,k);
ListPrint(L);
return 0;
}