當前位置:編程學習大全網 - 編程語言 - 用c語言實現單鏈表以及單鏈表的建立、清空、插入、刪除、查找、修改等運算。

用c語言實現單鏈表以及單鏈表的建立、清空、插入、刪除、查找、修改等運算。

程序如下:

#include?<string.h>

#include?<stdio.h>

#include?<stdlib.h>

struct?st

{long?num;

char?name[20];

float?score;

struct?st?*next;

};

/*?創建結點?*/

struct?st?*creat()

{struct?st?*head=NULL,*p,*q;

q=p=(struct?st?*)malloc(sizeof(struct?st));

scanf("%ld%s%f",&p->num,p->name,&p->score);

while(p->num)

{if(head==NULL)

head=p;

else

q->next=p;

q=p;

p=(struct?st?*)malloc(sizeof(struct?st));

scanf("%ld%s%f",&p->num,p->name,&p->score);

}

q->next=NULL;

free(p);

return?head;

}

/*?輸出結點?*/

void?print(struct?st?*p)

{printf("\n%s\t%s\t%s\n","號碼","姓名","總分");

while(p)

{printf("%03ld\t%s\t%.2f\n",p->num,p->name,p->score);

p=p->next;

}

printf("\n");

}

/*?刪除結點?*/

struct?st?*del(struct?st?*head,long?num)

{struct?st?*p=head,*q;

if(num==head->num)

head=head->next;

else

{do

{q=p;

p=p->next;

}while(p&&num!=p->num);

if(p)

q->next=q->next->next;

else

printf("\nerror!\n");

}

free(p);

return?head;

}

/*?插入結點?*/

struct?st?*insert(struct?st?*head,struct?st?*p)

{struct?st?*q=head;

if(p->num<head->num)

{p->next=head;

head=p;

}

else

{while(q->next&&p->num>q->next->num)

q=q->next;

p->next=q->next;

q->next=p;

}

return?head;

}

main()

{struct?st?*head,*p;

char?t[20];

long?num;

printf("?全功能鏈表\n");?

printf("\n%s\t%s\t%s\n","號碼","姓名","總分");

head=creat();

print(head);

printf("刪除(del)\插入(insert)\退出(exit):\n");

do

{scanf("%s",t);

if(strcmp(t,"del")==0)

{scanf("%ld",&num);

head=del(head,num);

}

else?if(strcmp(t,"insert")==0)

{p=(struct?st?*)malloc(sizeof(struct?st));

scanf("%ld%s%f",&p->num,p->name,&p->score);

head=insert(head,p);

}

else?if(strcmp(t,"exit")==0)

break;

else

printf("\nerror!\n");

print(head);

}while(1);

printf("完美結束!\n\n");

}

  • 上一篇:如何通過OPC自定義接口來實現客戶端數據的讀取
  • 下一篇:編程輸入小寫字母
  • copyright 2024編程學習大全網