單鏈表c語言實現的形式
包括初始化,創建,查詢,長度,刪除,清空,銷毀等操作
程式碼如下:
#include<stdio.h>
#include<stdlib.h>
//定義單鏈表的數據類型
typedef struct book
{
char name[10];
char code[10];
float price;
}book;
typedef book Book;
//定義單鏈表
typedef struct LNode
{
Book data;
struct LNode *next;
}LNode,*LinkList;
//初始化
void InitLNode(struct LNode*L)
{
L=(LNode*)malloc(sizeof(LNode));
if (!L)
{
printf("分配空間出錯,初始化失敗!");
exit(1);
}
L->next=NULL;
}
//頭插法,創建單鏈表
LNode* creatList(void)
{
LNode *head;
LNode *s;
LNode *p;
Book c;
head=(LNode*)malloc(sizeof(LNode));
p=head;
p->next=NULL;
printf("請輸入新節點的數據,當最後輸入的值小於等於0時建表完成,該值不接入鏈表\n");
scanf("%s%s%f",&c.name,&c.code,&c.price);
while (c.price>0)
{
s=(LNode*)malloc(sizeof(LNode));
s->next=p->next;
p->next=s;
s->data=c;
printf("請輸入書名,編碼和價格:\n");
scanf("%s%s%f",&c.name,&c.code,&c.price);
}
printf("creatList函數執行,創建鏈表成功\n");
return head;
}
//單鏈表的長度
int length(struct LNode *L)
{
int i=0;
LNode *p;
p=L;
while (p->next!=NULL)
{
i++;
p=p->next;
}
return i;
}
//單鏈表的插入
LNode* insertheadList(struct LNode* L,int i,Book b)
{
LNode *s,*p;
p=L;
int j=0;
if (i<=0)
{
printf("插入越界!\n");
exit(1);
}
while (p->next!=NULL)
{
if (j==i-1)
{
s=(LNode*)malloc(sizeof(LNode));
s->data=b;
s->next=p->next;
p->next=s;
printf("inserheadList函數執行,在第%d個位置插入了元素\n",j+1);
break;
}
p=p->next;
j++;
}
return L;
}
//單鏈表查詢
Book search(struct LNode*L,int i)
{
int j;
Book b;
LNode *p;
p=L;
if (i<0)
{
printf("查詢的節點越界了!");
exit(1);
}
j=1;
while (p->next!=NULL)
{
p=p->next;
if (j==i)
{
b=p->data;
break;
}
j++;
}
return b;
}
//單鏈表的刪除
Book DelList(struct LNode*L,int i)
{
Book b;
LNode *s,*p;
p=L;
int j;
if (i<1)
{
printf("刪除越界!\n");
exit(1);
}
j=0;
while (p->next!=NULL)
{
if (j==i-1)
{
s=p->next;
b=s->data;
p->next=s->next;
// printf("刪除第%d個節點成功,刪除的值為:name:%s,code:%s,price:%d\n",b.name,b.code,b.price);
free(s);
}
p=p->next;
j++;
}
return b;
}
//清空單鏈表
void ClearList(struct LNode*L)
{
LNode *p,*r;
p=L;
while (p)
{
p=p->next;
r=p;
free(p);
p=r;
}
L->next=NULL;
}
//銷毀單鏈表
void DestroyList(struct LNode*L)
{
LNode *p,*head;
head=L;
while (head)
{
p=head->next;
free(head);
head=p;
}
}
void main()
{
LNode L,*Q;
Book b;
int i;
Q=&L;
InitLNode(&L);
L=*creatList();
printf("請輸入書本的name,code和price:\n");
scanf("%s%s%f",&b.name,&b.code,&b.price);
insertheadList(&L,1,b);
int y=length(&L);
printf("單鏈表的length:%d\n",y);
//刪除第一個元素
Book bo= DelList(Q,1);
printf("刪除了第1個元素,它的name:%s,code:%s,price:%f\n",bo.name,bo.code,bo.price);
ClearList(Q);
printf("清空單鏈表成功!\n");
//按鏈表的存儲順序輸出
i=1;
while (Q->next!=NULL)
{
Book book=search(&L,i);
Q=Q->next;
printf("name:%s,code:%s,price:%f\n",Q->data.name,Q->data.code,Q->data.price);
i++;
}
}