对链表的综合操作

/*
*对链表的综合操作
*功能有建立,排序,插入,删除,输出
*/
#include<stdio.h>
#include<malloc.h>
typedef int ElemType;
typedef struct NodeType
{
 ElemType data;
 struct NodeType *next;
} NodeType,*LinkType;

LinkType create()
{//建立链表,返回链表的首地址,头结点没有数据
 LinkType head,p1,p2;
 head=(LinkType)malloc(sizeof(NodeType));
 p1=head;

 while(p1->data!=0)//当data=0时链表结束
 {
  p2=p1;
  p1=(LinkType)malloc(sizeof(NodeType));
  printf("Enter student's information:/ndata=");
  scanf("%d",&p1->data);
  p2->next=p1;
 }

 p2->next=NULL;
 free(p1);
 return(head);
}

void output(LinkType head)
{//链表的输出,接收链表的首地址
 head=head->next;

 while(head!=NULL)
 {
  printf("data=%d/n",head->data);
  head=head->next;
 }
}

LinkType sort(LinkType head)
{//链表排序,接收链表首地址,返回链表首地址
 LinkType ph,p1;
 ElemType temp;
 ph=head->next;
 p1=head->next;

 while(p1->next!=NULL)//冒泡法
 {
  ph=head;
  while(ph->next!=NULL)
  {
   if(ph->data>ph->next->data)//按data由小到大排序
   {
    temp=ph->data;
    ph->data=ph->next->data;
    ph->next->data=temp;
   }
   ph=ph->next;
  }
  p1=p1->next;
 }

 return(head);
}

LinkType del(LinkType head)
{//删除结点,接收链表的首地址,返回链表的首地址
 ElemType DelData;
 LinkType ph,p;
 ph=head->next;
 printf("Enter the data you want to del:/nDelData=");
 scanf("%d",&DelData);
 
 while(ph!=NULL && ph->data!=DelData)//寻找要删除的结点
 {
  p=ph;
  ph=ph->next;
 }

 if(ph==NULL)//没有找到要删除的结点
 {
  printf("Enter error!/n");
  return(head);
 }
 else
 {
  if(ph==head->next)//删除头结点
  {
   head->next=ph->next;
  }
  else//删除其它结点
  {
   p->next=ph->next;
  }
 }
 free(ph); 
 return(head);
}


LinkType insert(LinkType head)
{//插入结点,接收链表首地址,返回链表首地址
 LinkType ph,p,insert,temp;
 insert=(LinkType)malloc(sizeof(NodeType));
 printf("Enter the data you want to insert:/ndata=");
 scanf("%d",&insert->data);
 ph=head->next;

 while(ph!=NULL && ph->data < insert->data)//寻找插入的位置
 {
  p=ph;
  ph=ph->next;
 }
 if(head->next->data > insert->data)//插入头部
 {
  temp=head->next;
  head->next=insert;
  insert->next=temp;
 }
 else//插入到其它地方
 {
  p->next=insert;
  insert->next=ph;
 }
 return(head);

}

void main()
{
 LinkType head;
 head=create();
 output(head);
 printf("/n/n");

 head=sort(head);
 output(head);
 printf("/n/n");

 head=del(head);
 output(head);
 printf("/n/n");

 head=insert(head);
 output(head);
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值