#include <stdio.h>
#define _CRTDBG_MAP_ALLOC
#include <stdlib.h>
#include <crtdbg.h>
#define LEN (sizeof(node))
typedef int DATA;
typedef struct node
{
DATA data;
node * next ;
}node;
node * Create() //建立链表
{
DATA n;
node *head,*p1,*p2;
head=(node*) malloc(LEN);
if(NULL==head)
{
printf("Error,NO memory.");
return NULL;
}
printf("Enter numbers:\n");
scanf("%d",&n);
p1=head;
while(n!=-1)
{
p2=(node*) malloc(LEN);
p2->data=n;
p1->next=p2;
p1=p2;
scanf("%d",&n);
}
p2->next=NULL;
return head;
}
void Print(node *p) //打印链表
{
if(p==NULL)
{
printf("List Error!");
return ;
}
printf("\n The list num are:\n");
p=p->next;
while(p!=NULL)
{
printf("%d,",p->data);
p=p->next;
}
printf("\n");
}
void Destroy(node *p) //销毁链表
{
if(p==NULL)
{
printf("Error list");
return ;
}
node *p1=p;
while(p1->next!=NULL)
{
p1=p->next ;
free(p);
p=p1;
}
free(p1);
p1=NULL;
}
void ClearList(node *p) //清空链表
{
if(NULL==p)
{
printf("Error list");
return ;
}
node *p1=p;
while(p->next !=NULL)
{
p->data =0;
p=p->next ;
}
p->data =0;
}
int ListLength(node *head)//链表长度
{
if(head==NULL)
{
printf("Error List");
return -1;
}
int i=0;
while(head->next !=NULL)
{
i++;
head=head->next ;
}
return i;
}
node * NewNode(node *head,int n) //在链表尾端添加节点
{
if(head==NULL||n==-1)
{
printf("Wrong Data!");
return NULL;
}
node *p1=head;
while(head->next !=NULL)
head=head->next ;
node *p=(node *)malloc(LEN);
p->data =n;
head->next =p;
p->next =NULL;
return p1;
}
node * DelNode(node *head,int n) //删除节点
{
if(head==NULL||n==-1)
{
printf("Wrong NUM");
return NULL;
}
node *p=head,*p1=head;
while(head->next !=NULL)
{
p=head;
head=head->next ;
if(head->data ==n)
{
p->next =head->next ;
free(head);
break;
}
}
return p1;
}
node * Sort(node * head) //排序
{
if(NULL==head)
{
printf("Wrong List");
return NULL;
}
node *i=head,*j=head;
DATA temp;
for (i=head->next ;i->next !=NULL;i=i->next )
for(j=i->next;j!=NULL;j=j->next)
{
if(i->data >j->data)
{
temp=i->data ;
i->data =j->data ;
j->data =temp;
}
}
return head;
}
node *Reverse(node *head)//链表逆置
{
if(head==NULL)
{
printf("Wrong num!");
return NULL;
}
node *p,*s,*r;
p=head->next ;
r=s=p->next ;
p->next =NULL;
while(s!=NULL)
{
s=r->next ;
r->next=p;
p=r;
r=s ;
}
head->next =p;
return head;
}
int main()
{
_CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF|_CRTDBG_LEAK_CHECK_DF);
node *p=Create();
Print(p);
int num=0;
printf("\n there are %d nums.",ListLength(p));
printf("\n Enter the num you want to add: ");
scanf("%d",&num);
NewNode(p,num);
printf("\n");
Print(p);
Sort(p);
Print(p);
printf("Enter the num you want to delete: ");
scanf("%d",&num);
DelNode(p,num);
Print(p);
Reverse(p);
Print(p);
ClearList(p);
Print(p);
Destroy(p);
_CrtDumpMemoryLeaks();
return 0;
}
链表的建立,插入,逆置,测长操作
最新推荐文章于 2025-04-13 14:36:48 发布