实验十三 链表的处理

u    实验目的

1、掌握链表的数据组织形式

2、掌握链表的相关操作(建立、排序、插入、删除)

u    预习内容

见教材第十一章

u    实验重点

1、掌握链表的数据组织形式

2、掌握链表的相关操作

u    实验难点

掌握链表的概念,初步学会对链表进行常见操作。

u    实验内容

编程序并上机调试运行:(本题要求用链表实现。)

建立一个链表,每个结点包括:学号、姓名、性别、年龄。输入一个年龄,如果链表中的结点所包含的年龄等于此年龄,则将此结点删去。

u    参考例题

【例】建立一个三个结点的链表,存放学生数据。为简单起见, 我们假定学生数据结构中只有学号和年龄两项。

可编写一个建立链表的函数creat。程序如下:

#include "stdio.h"

#include "stdlib.h"

#define NULL 0

#define TYPE struct stu

#define LEN sizeof (struct stu)

struct stu

    {

      int num;

      int age;

      struct stu *next;

    };

TYPE *creat(int n)

{

    struct stu *head,*pf,*pb;

    int i;

    for(i=0;i<n;i++)

    {   

      pb=(TYPE*) malloc(LEN);

      printf("input Number and  Age\n");

      scanf("%d%d",&pb->num,&pb->age);

      if(i==0)

       pf=head=pb;

       else pf->next=pb;

       pb->next=NULL;

       pf=pb;

     }

     return(head);

}

 

    void out(struct stu *h)

    {

        struct stu *p;

        p=h;

        printf("\nNow output:");

        while(p!=NULL)

        {

            printf("\n%d   %d",p->num,p->age);

            p=p->next;

        }

        return ;

    }

struct stu *insert(struct stu *h)

    {

       struct stu *p,*q,*p1;

       int n,i;//插入 位置

       scanf("%d",&n);

       if(n<1)printf("\n位置 非法");

       else

       {

       p=h;

           i=1;

           while(i<n-1&&p!=NULL)

           {

              p=p->next;

              i++;

           }

           if(p==NULL)

                printf("\n位置 非法");

           else

           {

              q=(struct stu*)malloc(sizeof(LEN));

              printf("input Number and  Age\n");

             scanf("%d%d",&q->num,&q->age);

              if(n==1)

              {

                 q->next=h;

                 h=q;

               }

               else

               {

                   q->next=p->next;

                   p->next=q;

                }

            }

        }

        return h;

    }

struct stu *del(struct stu *head,int num)

{struct stu *p1,*p2;

if(head==NULL) {printf(“\n list null!\n”); return(head);}

p1=head;

while(num!=p1->num && p1->next!=NULL)

{P2=P1; P1=P1->next;}

if(num==p1->num)

{if(p1==head)head=p1->next;

else p2->next=p1->next;

printf(“delete:%d\n”,num);

n=n-1;

}

else printf(“%d not be found!\n”,num);

return head;

}

    void main()

    {

        struct stu *h;

        int n;

        scanf("%d",&n);

        h=creat(n);

        out(h);

        h=insert(h);

        out(h);

h=del(h);

        out(h);

    }

公告通知
教学日历
疑难留言
同学你好!对本课程有哪些建议?