包含创建,反转,,反转,去重,反转
#include<cstdio>
#include<stdlib.h>
#include<iostream>
using namespace std;
typedef struct list_node{
int info;
struct list_node *next;
}node;
node *newlist()
{
int x,z;
node *head=(node*)malloc(sizeof(node));
if(head==NULL)
{
printf("分配失败\n");
exit(-1);
}
node *tail=head;
tail->next=NULL;
printf("输入链表长度:");
scanf("%d",&x);
for(int i=0;i<x;i++)
{
printf("请输入第%d个:",i+1);
scanf("%d",&z);
node *ne=(node*)malloc(sizeof(node));
if(ne==NULL)
{
printf("分配内存失败\n");
exit(-1);
}
ne->info=z;
tail->next=ne;
ne->next=NULL;
tail=ne;
}
return head;
}
void display(node *head)
{
node *p;
p=head->next;
if(!p){printf("单链表为空!\n");}
while(p)
{
printf("%-5d",p->info);
p=p->next;
}
printf("\n");
}
node *Reverse(node *head)///带头结点的单链表反转
{
node *q,*pre,*r;
q=head->next;
if(!q){
printf("该单链表为空\n");
return head;
}
pre=q->next;
if(!pre) return head;///单链表长度为1,不用反转
while(pre)
{
r=pre->next;///保存pre的下一节点地址
pre->next=q;///反转
q=pre; ///移位
pre=r; ///移位
}
head->next->next=NULL;
head->next=q;///因为带头结点,所以是pre不是q!!
printf("反转结束\n");
return head;
}
void insert1(node *head)///顺序插入
{
int x;
printf("输入插入的数\n");
scanf("%d",&x);
node *q,*pre,*p;
q=head->next;
pre=head; ///如果x大于链表首结点,直接插入到(pre)head后面
while(q&&q->info<=x)
{
pre=q;
q=q->next;
}
p=(node*)malloc(sizeof(node));
p->info=x;
pre->next=p;
p->next=q;
printf("插入完成\n");
}
void repeatdelete(node *head)
{
node *p,*q,*r;
p=head->next;
while(p)
{
q=p;
while(q->next)
{
if(q->next->info==p->info)
{
r=q->next;
q->next=r->next;
free(r);
}
else q=q->next;
}
p=p->next;
}
printf("已经去重\n");
}
void sort1(node *head)///排序
{
node *p,*pre,*z;
int t;
p=head->next;
z=head->next;
if(!p){
printf("链表为空,不用排序\n");
return ;
}
pre=p->next;
if(!pre){
printf("单链表长度为1,不用排序\n");
return ;
}
while(z)
{
p=head->next;
pre=p->next;
while(pre)
{
if(pre->info>p->info)
{
t=pre->info;///相当于swap
pre->info=p->info;
p->info=t;
}
p=p->next;///移位
pre=p->next;
}
z=z->next;///z用与第一层循环计数
}
printf("排序完成\n");
}
void free1(node *head)
{
node *p,*q;
p=head->next;
while(p)
{
q=p->next;
free(p);
p=q;
}
head->next=NULL;
}
int main()
{
node *head;
head=newlist();///创建
display(head);
Reverse(head);///反转
display(head);
insert1(head);///顺序插入
display(head);
repeatdelete(head);///去重
display(head);
sort1(head);///排序
display(head);
free1(head);
display(head);
return 0;
}