#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <Windows.h>
struct node
{
int data;
struct node* next;
};
//初始化
struct node* InitSingleList()
{
struct node* list = malloc(sizeof(struct node));
if (list == NULL)
return NULL;
list->data = 0;
list->next = NULL;
return list;
}
//尾插法创建链表
void CreateSingleListByTail(struct node* list)
{
struct node* pmove, * pcreate, * head;
int len, data;
head = (struct ndoe*)malloc(sizeof(struct node));
head = list;
if (head == NULL)
return;
else
head->next = NULL;
pmove = head;
printf("请输入要创建的单链表的长度:");
scanf_s("%d", &len);
printf("请输入数据:\n");
for (int i = 0; i < len; i++)
{
scanf_s("%d", &data);
pcreate = (struct node*)malloc(sizeof(struct node));
if (pcreate == NULL)
return;
else
{
pcreate->data = data;
pcreate->next = NULL;
}
//尾插操作
pmove->next = pcreate;
pmove = pcreate;
}
}
//求链表长度
int ForeachSingleList(struct node* list)
{
int num = 0;
struct node* pmove;
pmove = list->next;
while (pmove != NULL)
{
num++;
pmove = pmove->next;
}
return num;
}
//对链表的后一半进行逆置
void ReverseSingleList(struct node* list)
{
struct node* pmove, * pre, * save, * qmove;
pmove = list->next;
pre = NULL;
int size, i = 1;
size = ForeachSingleList(list) / 2;
while (i < size)//找中间结点
{
pmove = pmove->next;
i++;
}
//对链表后一半逆置
qmove = pmove->next;
while (qmove != NULL)
{
save = qmove->next;
qmove->next = pre;
pre = qmove;
qmove = save;
}
pmove->next = pre;
}
//将逆置后的一半插入到前一半链表
void InsertSingleList(struct node* list)
{
struct node* pmove, * qmove, * save, * save1;
int i = 1, size, j = 1;
size = ForeachSingleList(list) / 2;
pmove = list->next;
while (i < size)//找链表中间结点
{
pmove = pmove->next;
i++;
}
//处理后一半链表
qmove = pmove->next;
pmove = list->next;
while (j < size)
{
//分别保存pmove和qmove的后继结点
save = qmove->next;
save1 = pmove->next;
//将链表的后一半插入到前一半
qmove->next = pmove->next;
pmove->next = qmove;
//一个结点处理完成后,两个指针分别下移
qmove = save;
pmove = save1;
j++;
}
pmove->next = qmove;
}
void Show(struct node* list)
{
struct node* pmove;
pmove = list->next;
while (pmove != NULL)
{
printf("%d ", pmove->data);
pmove = pmove->next;
}
printf("\n");
}
//销毁单链表
void destory_SingleList(struct node* list)
{
struct node* currentNode,* nextNode;
currentNode = list->next;
while (currentNode != NULL)
{
nextNode = currentNode->next;
free(currentNode);
currentNode = nextNode;
}
free(list);
list = NULL;
}
int main(void)
{
struct node* list;
list = InitSingleList();
CreateSingleListByTail(list);
printf("初始链表数据为:\n");
Show(list);
printf("逆置后的链表为:\n");
ReverseSingleList(list);
Show(list);
InsertSingleList(list);
printf("最终的链表为:\n");
Show(list);
destory_SingleList(list);
system("pause");
return EXIT_SUCCESS;
}