• 转贴:C语言链表基本操作


    http://www.oschina.net/code/snippet_252667_27314#comments

    这个代码有很多错误,估计是从老谭书上抄来但是很多还抄错了:对照老谭的书好好研究下。切记!

    p2是p1的跟屁虫!切记

    #include"stdio.h"
    #include"malloc.h"
    struct stu
    {
        int num;//这个是学号
        float score;//这个是分数
        struct stu *next;
    };
    struct stu*create()
    {
        int n;//这个n这里不大合适 ,最好弄个全局的
        struct stu *head,*p1,*p2;
        p1=p2=(struct stu*)malloc(sizeof(struct stu));
        scanf("%d %f",&p1->num,&p1->score);
        head=NULL;
        n=0;
        while(p1->num!=0)
        {
            n++;
            if(n==1)head=p1;
            else
            {
                p2->next=p1;
                p2=p1;
                p1=(struct stu*)malloc(sizeof(struct stu));
                scanf("%d %f",&p1->num,&p1->score);
            }
        }
        p2->next=NULL;
        return head;
    };
    //难点在插入操作的实现上(默认从小到大排列的)
    struct stu *insert(struct stu *head,struct stu *stud)
    {
        struct stu *p0,*p1,*p2;
        p1=head;
        p0=stud;
        while((p0->num>p1->num)&&(p1->next!=NULL))
        {
            p2=p1;
            p1=p1->next;
        }
        if(p0->num<p1->num)//能在队列中插入(不是尾巴)
        {
            if(head==p1)head=p0;//在头部前插入
            else//在非头部插入
            {
                p2->next=p0;
                p0->next=p1;
            }
        }
        else//在尾巴插入
        {
            p1->next=p0;
            p0->next=NULL;
        }
      //这个地方要怎么维护总的num呢 ? return head; }; //删除操作难度次之 struct stu *del(struct stu *head,int num) { struct stu *p1,*p2; p1=head; if(head!=NULL) { while((p1->num<num)&&(p1->next!=NULL)) { p2=p1; p1=p1->next; } if(num==p1->num)//找到节点了 {   //这里要考虑删除头节点的情况 p2->next=p1->next; p2=p1;
          //要考虑删除的节点内存释放
          //要考虑维护n的数目
    } else//没有找到节点 { printf("NO Result!!! "); } } else printf("The linklist is EMPTY "); return head; }; void print(struct stu *head) { struct stu *p; p=head; while(p) { printf("%d %f ",p->num,p->score); p=p->next; } } void main() { int n; struct stu *create(); struct stu *insert(struct stu *head,struct stu *stud); void print(struct stu *head); struct stu *head,*p,*p1; head=create(); p=head; print(p); printf("please input : "); scanf("%d %f",&p1->num,&p1->score); p=insert(head,p1); print(p); printf("please input the del num: "); scanf("%d",&n); p=del(head,n); print(p); }
  • 相关阅读:
    JWT在flask中的demo
    14.Android开发笔记:碎片(Fragment)
    13.Android开发笔记:界面开发最佳实践
    12.Android开发笔记:RecyclerView
    11.Android开发笔记:ListView
    10.Android开发笔记:布局控件(五) 自定义控件
    9.Android开发笔记:布局控件(四) 百分比布局
    8.Android开发笔记:布局控件(三)FrameLayout 帧布局
    7.Android开发笔记:布局控件(二)RelativeLayout 相对布局
    6.Android开发笔记:布局控件(一)LinearLayout 线性布局
  • 原文地址:https://www.cnblogs.com/jeanschen/p/3542668.html
Copyright © 2020-2023  润新知