单链表

#include<stdio.h>
#include<stdlib.h>

struct chain
{
 int value;
 struct chain *next;
};

struct chain *create()
{
 struct chain *head,*tail,*p;
 int x;
 head = tail = NULL;
 while(scanf("%d",&x)==1)
 {
  p=(struct chain*)malloc(sizeof(struct chain));
  p->value=x;
  p->next=NULL;
  if(head==NULL)
   head = tail = p;
  else
   tail=tail->next=p;
 }
 return head;
}

struct chain *inlink(struct chain *head,int a,int b)    //int a代表要插入的节点,int b代表创建节点的数据域
{
 struct chain *p,*q,*s;
 s = (struct chain *)malloc(sizeof(struct chain));
 s->value=b;
 if(head==NULL)
 {
  head = s;
  head->next = NULL;
 }
 if(head->value == a)
 {
  s->next=head;
  head = s;
 }
 else
 {
  p=head;
  while((p->value!=a)&&(p->next!=NULL))
  {
   q=p;
   p=p->next;
  }
  if(p->value == a)
  {
   q->next = s;
   s->next = p;
  }
  else
  {
   p->next=s;
   s->next=NULL;
  }
 }
 return (head);
}

struct chain *dellink(struct chain *head,int a)  //int a代表要删除的节点
{
 struct chain *q,*p;
 if(head == NULL)
  printf("找不到节点!\n");
 else if(head->value == a)
 {
  p = head;
  head = head->next;
 }
 else
 {
  p=head;
  while((p->value!=a)&&(p->next!=NULL))
  {
   q=p;
   p=p->next;
  }
  if(p->value != a)
   printf("链表不存在此节点!\n");
  else
  {
   q->next = p->next;
   free(p);
  }
 }
 return (head);
}

void main()
{
 struct chain *p,*q;
 //q=create();                   //链表的创建;
 q=inlink(create(),3,0);       //链表的插入;
 //q=dellink(create(),2);          //链表的删除;
 while(q){                       //输出链表;
  printf("%d ",q->value);
  p=q->next;
  free(q);
  q=p;
 }
 printf("\n");
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值