2012—07—12 单链表

            以前学C语言的时候,单链表的内容,老师没有仔细的讲。考二级的时候,遇到比较难的也是放弃了。从来木有好好研究过。由于昨天阶段性测试的原因,有关于单链表的题目,实在是无从下手,所以只好把书拿出来翻翻,可是书上讲的也不是很详细,只好在博客上搜了一些相关的内容看了一下,再结合当时上课记的笔记和考级前的培训,就写了些程序。

 #include  <stdio.h>
struct slink
{int data;
 struct slink *next
};

一、建表
从键盘输入数值,只要不是-1,产生结点,-1表示建表结束。 
1.头插法
struct slink *creat1( )
{  struct link *head,*new;
   int x;
   head=NULL;
   scanf("%d",&x);
   while(x!= -1)
   { new=(struct slink *)malloc(sizeof(struct slink));
      new->data=x;
      new->next=head;
      head=new;
      scanf("%d",&x);
   }
  return head;
}
2.尾插法
struct slink *creat2( )
{  struct slink *head,*new,*rear;
   int x;
   head=NULL;
   scanf("%d",&x);
   while(x!= -1)
   { new=(struct slink *)malloc(sizeof(struct slink));
      new->data=x;
      if(head==NULL) head=new;
      else  rear->next=new;
      rear=new;
     scanf("%d",&x);
   }
   rear->next=NULL;
   return head;
}

二、插入
1.p结点之后插入
    new->next=p->next;
    p->next=new;

2.p结点之前插入
struct slink *insert(struct slink *head,int x,int y)
/*规定:找不着x结点,y插入在表尾*/
{struct link *p,*q,*new;
 new=(struct slink *)malloc(sizeof(struct slink));
 new->data=y;
 p=head;
 while(p!=NULL)                                            
 { if(p->data!=x)
      {  q=p;  p=p->next;}
   else break;
 }
if(p==head) {new->next=head; head=new;}
else
{ new->next=q->next;   q->next=new;}
return head;
}

三、删除
1.删除p后继结点
t=p->next;
p->next=t->next;
free(t);
2.删除p自身
struct slink *delete(struct slink *head,int x)
{ struct slink *p,*q;
   p=head;
   while(p!=NULL)
   {  if(p->data!=x)  {  q=p;  p=p->next;}
       else
      { if(p==head) head=p->next;
        else q->next=p->next;
         free(p);
       }
   }
  return head;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值