线性链表(算法没有考虑时间和空间复杂度)
/*线性链表的初始化,添加,删除,显示*/
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
typedef struct listtable{
int num;
char name[10];
struct listtable *next;
}ListTable;
int n;/*记录成员个数*/
struct listtable * Init_listtable(void)/*线性链表的初始化*/
{
n=0;
struct listtable * head;
if(!(head=(ListTable *)malloc(sizeof(ListTable))))exit(0);
head->next=0;
return head;
}
void Add_listtable(ListTable *head)/*线性链表的添加*/
{
struct listtable *p1;
if(!(p1=(ListTable *)malloc(sizeof(ListTable)))){exit(0);}
printf("please input your add data:\n");
printf("num :");scanf("%d",&p1->num);
printf("name :");scanf("%s",&p1->name);
if(head->next==NULL){
p1->next=NULL;
}
else{p1->next=head->next;}
head->next=p1;
n++;
}
void Del_listtable(ListTable *head)/*线性链表的删除*/
{
int num;
struct listtable *p2,*p3;
p3=head;
printf("please input your del number:\n");
printf("num : ");scanf("%d",&num);
p2=p3->next;
while(p3&&p2){
if(num!=p2->num)
{
if(p2->next!=NULL){
p2=p2->next;p3=p3->next;
}
else {
exit(0);
}
}
else{
p3->next=p2->next;
free(p2);
n--;
break;
}
}
}
void Print_listtable(ListTable *head)/*显示数据*/
{
int i;
struct listtable *p1;
p1=head->next;
printf("Now the listtable have %d data:\n",n);
if(p1)
{
for(i=0;i<n;i++)
{
printf("num [%d] : %d\t",(i+1),p1->num);
printf("name [%d] : %s\n",(i+1),p1->name);
p1=p1->next;
}
}
else {printf("No data!\n");}
}
int main()
{
struct listtable *head;
head=Init_listtable();
Add_listtable(head);
Add_listtable(head);
Add_listtable(head);
Add_listtable(head);
Print_listtable(head);
Del_listtable(head);
Print_listtable(head);
Del_listtable(head);
Print_listtable(head);
Del_listtable(head);
Print_listtable(head);
Del_listtable(head);
Print_listtable(head);
return 0;
}