您的位置:首页 > 编程语言 > C语言/C++

单链表的创建、增加、删除、清空操作

2015-10-06 19:49 537 查看
用C语言实现单链表的几个基本操作:创建(分从头创建和从尾创建)、增加、删除、清空操作:

#include<stdio.h>
#include<malloc.h>

typedef struct Node
{
int data;
struct Node *next;
}Node;

Node *CreatebyTail();//新建链表,从尾部插入结点
Node *CreatebyHead();//新建链表,从首部插入结点
void Print(Node *head);//打印链表
Node *Insert(Node *head,int num);//从链表尾部插入num元素
Node *Delete(Node *head,int num);//从链表中删除num元素
void Clear(Node *head);//清空链表

int main()
{
Node *head;
int m,n;
head=CreatebyTail();
//head=CreatebyHead();
Print(head);
printf("输入要插入的数:\n");
scanf("%d",&n);
head=Insert(head,n);
printf("插入之后,");
Print(head);
printf("输入要删除的数:\n");
scanf("%d",&m);
head=Delete(head,m);
printf("删除之后,");
Print(head);
Clear(head);
return 0;
}

Node *CreatebyTail()//新建链表,从尾部插入结点
{
Node *head,*tail,*p;
int num;
head=tail=NULL;
printf("输入数据并以-10000结尾:\n");
scanf("%d",&num);
while(num!=-10000)
{
p=(Node*)malloc(sizeof(Node));
p->data = num;
p->next = NULL;
if(head==NULL)//如果此时链表中没有任何数据
{
head=p;
}
else//如果此时链表中已有一些数据
{
tail->next=p;
}
tail=p;
scanf("%d" , &num);
}
return head;
}

Node *CreatebyHead()//新建链表,从首部插入结点
{   Node *head,*p;
int num;
head=(Node*)malloc(sizeof(Node));
head->next=NULL;
printf("输入数据并以-10000结尾:\n");
scanf("%d",&num);
while(num!=-10000)
{
p=(Node*)malloc(sizeof(Node));
p->data=num;
p->next=head->next;
head->next=p;
scanf("%d",&num);
}
return head;
}

void Print(Node *head)//打印链表
{
Node *p;
p=head;//从尾部插入时
//p=head->next;//从首部插入时
if(head==NULL)
{
printf("链表为空!\n");
}
else
{
printf("链表如下:\n");
while(p != NULL)
{
printf("%4d",p->data);//输出数据占4个位置,不足的在左边补空格
p=p->next;
}
}
printf("\n");
}

Node *Delete(Node *head,int num)//从链表中删除num元素
{
Node *p1,*p2;
if(head==NULL)
{
printf("链表为空!\n");
return head;
}
p1=head;
while( p1->next && p1->data != num )//若p1还没指向最后一个结点,则不断后移去寻找num元素
{
p2=p1;//p2与p1一起移动
p1=p1->next;
}
if( p1->data == num )//此时p1指向了num元素
{
if( head == p1 )//如果p1指向了头结点
{
head=p1->next;
}
else
{
p2->next=p1->next;
}
free(p1);
printf("删除成功!\n");
}
else
{
printf("无此数据!\n");
}
return head;
}

Node *Insert(Node *head,int num)//从链表尾部插入num元素
{
Node *p,*p1,*p2;
p=(Node*)malloc(sizeof(Node));
p->data=num;
p->next=NULL;
p1=head;
while(p1)//p1不断后移直至指向了最后一个结点
{
p2=p1;
p1=p1->next;
}
if(p1 == head)
{
head=p;
}
else
{
p2->next=p;
}
p->next=p1;
printf("数据插入成功!\n");
return head;
}

void Clear(Node *head)//清空链表
{
Node *p=head;
while(head)
{
p=head->next;
free(head);
head=p;
}
printf("链表已清空!\n");
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  c语言 单链表