注意:創(chuàng)建節(jié)點(diǎn),一定要銷毀節(jié)點(diǎn)。
#include <stdio.h>
#include <stdlib.h>
typedef struct node{
intdata;
structnode *next;
} node_t;
// 創(chuàng)建節(jié)點(diǎn)函數(shù)
void *create(int size);
// 初始化鏈表
int init(node_t *head);
// 頭插入法
int insert_head(node_t *head,node_t *pn);
// 尾插入法
int insert_end(node_t *head,node_t *pn);
// 打印所有節(jié)點(diǎn)內(nèi)容
void print(node_t *head);
// 銷毀所有節(jié)點(diǎn)
void destroy(node_t *head);
// 應(yīng)用函數(shù)
// 創(chuàng)建長(zhǎng)度為 len 的鏈表并輸入內(nèi)容
int create_link(node_t *head,int len);
int main()
{
node_t*head = NULL;
intlen = 0;
if(init(head= create(sizeof(node_t))) != 0){
printf("初始化鏈表失敗\n");
exit(0);
}
printf("長(zhǎng)度:");
scanf("%d",&len);
create_link(head,len);
print(head);
destroy(head);
free(head);
head= NULL;
return0;
}
// 創(chuàng)建節(jié)點(diǎn)函數(shù)
// 成功返回新節(jié)點(diǎn)首地址,失敗返回 NULL
void *create(int size)
{
returncalloc(1,size);
}
// 初始化鏈表
// 0-成功 1-失敗
int init(node_t *head)
{
if(NULL== head)
return1;
head->next= NULL;
return0;
}
// 頭插入法
// 0-成功 1-失敗
int insert_head(node_t *head,node_t *pn)
{
if(NULL== pn)
return1;
pn->next= head->next;
head->next= pn;
return0;
}
// 尾插入法
// 0-成功 1-失敗
int insert_end(node_t *head,node_t *pn)
{
node_t*tail = NULL;
if(NULL== pn)
return1;
tail= head;
while(tail->next!= NULL)
tail= tail->next;
tail->next= pn;
pn->next= NULL;
return0;
}
// 打印所有節(jié)點(diǎn)內(nèi)容
void print(node_t *head)
{
node_t*cur = NULL;
cur= head->next;
while(cur!= NULL){
printf("%d",cur->data);
cur= cur->next;
}
printf("\n");
}
// 銷毀所有節(jié)點(diǎn)
void destroy(node_t *head)
{
node_t*del =NULL,*n_node = NULL;
del = head->next;
while(del != NULL){
n_node= del->next;
free(del);
del = n_node;
}
init(head);
}
// 應(yīng)用函數(shù)
// 創(chuàng)建長(zhǎng)度為 len 的鏈表并輸入內(nèi)容
// 返回創(chuàng)建的節(jié)點(diǎn)數(shù)
int create_link(node_t *head,int len)
{
inti = 0;
node_t*n_node = NULL;
printf("輸入 %d 個(gè)數(shù):\n",len);
for(i= 0;i < len;i++){
n_node= create(sizeof(node_t));//創(chuàng)建新節(jié)點(diǎn)
if(NULL== n_node)
returni;
scanf("%d",&n_node->data); // 輸入數(shù)據(jù)
insert_end(head,n_node); // 插入鏈表
}
returni;
}