单链表的创建、插入、删除、倒置操作[1]

[入库:2005年8月19日] [更新:2007年3月24日]

本文简介:选择自 smoilbig 的 blog

/*-----------------------------------------------------*/
/*--------------单链表的创建、插入、删除、倒置操作-----------*/
/*--------------written by redfire250-----2005.5.10----*/
/*-----------------------------------------------------*/

#include<malloc.h>
#include<stdio.h>
#define null 0
struct student
{
 long number;
 char name[20];
 long score;
 struct student *next;
};

int n=0;/*n为全局变量,用来计算链表的结点个数*/

 

/*-----------------------------------------*/
/*--------------创建结点函数creat()--------*/
/*-----------------------------------------*/
struct student *creat()
{

  struct student *p1;
  struct student *p2;
  struct student *head=null;
  p1=p2=(struct student *)malloc(sizeof(struct student));/*开辟一段可用内存单元*/
  printf("please input the student's number name and the score:\n");
  scanf("%ld%s%ld",&p2->number,p2->name,&p2->score);

  while(p2->number!=0)
  {
      n++;

      if(n==1)            /*是否开辟的是第一个结点*/
      head=p2;
      else
      p1->next=p2;

      p1=p2;
      p2=(struct student *)malloc(sizeof(struct student));
      printf("input the  number the name and the score:\n");
      scanf("%ld%s%ld",&p2->number,p2->name,&p2->score);
  }
  p1->next=null;
  return(head);
}


/*------------------------------------------*/
/*--------------查看链表内容函数view()------*/
/*------------------------------------------*/
 view(struct student *head)
 {
  struct student *p;
  p=head;
  while(p->next!=null)
  {
       printf("%ld  %s  %ld\n",p->number,p->name,p->score);
       p=p->next;
  }
  printf("%ld  %s  %ld\n",p->number,p->name,p->score);
 }

 

/*-------------------------------------------------*/
/*--------------插入结点函数(前插)insert()-------*/
/*-------------------------------------------------*/
 insert(struct student *head,int num)       /*head为链表头指针,num插入链表位置*/
{
 int t=1;
 struct student *p1,*p2;
 p1=head;
 if (num>n||num<0)
 {
     printf("input error!!!\n");
     return 0;
 }
 
 while(t<num-1)                  /*找到要插入结点的前一个结点*/
 {
     p1=p1->next;
     t++;
 }
 p2=(struct student *)malloc(sizeof(struct student));
 printf("input the  number the name and the score:\n");
 scanf("%ld%s%ld",&p2->number,p2->name,&p2->score);
 p2->next=p1->next;
 p1->next=p2;
 n++;

}


/*------------------------------------------*/
/*------------ 删除结点函数delnode()--------*/
/*-----------------------------------------*/
 delnode(struct student *head,int node)
{
 int t=1;
 struct student *p1,*p2;
 p2=head;
 if (node>n||node<1)
 {
     printf("error!!! the node is not exist!");
     return 0;
 }
 while(t<node-1)       /*找到要删除结点的前一个结点*/
 {
     p2=p2->next;
     t++;
 }
 p1=p2->next->next;     /*找到要删除结点的后一个结点*/
 free(p2->next);        /*释放要删除的结点空间(删除)*/
 p2->next=p1;           /*前一结点指向后一结点*/
 n--;          
}

本文关键:单链表的创建、插入、删除、倒置操作
 

本站最佳浏览方式为 分辨率 1024x768 IE 6.0(或更高版本的 IE浏览器)

go top