2012—07—12 单链表

来源:互联网 发布:我要开淘宝网店 编辑:程序博客网 时间:2024/06/01 07:33

            以前学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;
}

原创粉丝点击