双向链表(简单的实现其功能)
/*双向链表的初始化,添加,删除,显示*/
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
typedef struct two_linklist{
int num;
char name[20];
struct two_linklist *next;
struct two_linklist *prior;
}Two_Linklist;
int n;/*数据个数*/
struct two_linklist * Init_Two_Linklist(void)/*双向链表初始化*/
{
n=0;
struct two_linklist * head;
if(!(head=(Two_Linklist *)malloc(sizeof(Two_Linklist)))){return 0;}
head->next=head;
head->prior=head;
return head;
}
void Add_Two_Linklist(struct two_linklist *head)/*双向链表添加*/
{
struct two_linklist *p1,*p2;
if(!(p1=(Two_Linklist *)malloc(sizeof(Two_Linklist))))exit(0);
p2=head->next;
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=p1;
p1->prior=p1;
}
else{
p1->prior=p2->prior;
head->next=p1;
p1->next=p2;
p2->prior=p1;
}
head->next=p1;
n++;
}
void Del_Two_Linklist(struct two_linklist *head)/*双向链表删除*/
{
int num,k;
k=n;
struct two_linklist *p2,*p3;
p2=head;
printf("please input your del data:\n");
printf("num : ");scanf("%d",&num);
p2=p2->next;
while(p2){
if(num!=p2->num){
if(k--){p2=p2->next;}
else{exit(0);}
}
else{
p2->prior->next=p2->next;
p2->next->prior=p2->prior;
free(p2);n--;
break;
}
}
}
void Print_Two_Linklist(struct two_linklist *head)/*显示数据*/
{
int i;
struct two_linklist *p1;
p1=head;
printf("Now the two_linklist have %d data:\n",n);
if(p1)
{
for(i=0;i<n;i++)
{
p1=p1->prior;
printf("num [%d] : %d\t",(i+1),p1->num);
printf("name [%d] : %s\n",(i+1),p1->name);
}
}
else{printf("No data!\n");}
}
int main(int argc,char **argv)
{
printf("please input your data!\n");
struct two_linklist *head;
head=Init_Two_Linklist();
Add_Two_Linklist(head);
Add_Two_Linklist(head);
Add_Two_Linklist(head);
Print_Two_Linklist(head);
Del_Two_Linklist(head);
Print_Two_Linklist(head);
Del_Two_Linklist(head);
Print_Two_Linklist(head);
Del_Two_Linklist(head);
Print_Two_Linklist(head);
return 0;
}
浙公网安备 33010602011771号