zoukankan      html  css  js  c++  java
  • 转贴: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); }
  • 相关阅读:
    JQ优化性能
    CSS3 Filter的十种特效
    立即执行函数: (function ( ){...})( ) 与 (function ( ){...}( )) 有什么区别?
    EasyUI DateBox
    Java8接口的默认方法
    MySQL -- insert ignore语句
    建数据库表经验总结
    IntelliJ IDEA 实用快捷键
    从 Java 代码到 CPU 指令
    使用ImmutableMap简化语句
  • 原文地址:https://www.cnblogs.com/jeanschen/p/3542668.html
Copyright © 2011-2022 走看看