C语言 带有头结点的单链表的实现和相关操作。
#include<stdio.h>
#include<stdlib.h>
typedef int ADT;
typedef struct node
{
ADT data;
struct node *next;
}Node;
typedef struct
{
Node *head;
unsigned size;
} list;
void init_list(list *lp)
{
lp->head=NULL;
lp->size=0;
}
Node* make_node(int data)
{
Node *newnode=(Node*)malloc(sizeof(Node));
if(newnode==NULL)
return;
newnode->data =data;
newnode->next=NULL;
return newnode;
}
void push_back_list(list *lp,int data)
{
Node *newnode=make_node(data);
if(lp->head ==NULL)
{
lp->head =newnode;
lp->size ++;
return;
}
Node *cur=lp->head ;
while(cur->next)
cur=cur->next ;
cur->next=newnode;
lp->size++;
}
void push_frout_list(list *lp,int data)
{
Node *newnode=make_node(data);
newnode->next=lp->head;
lp->head=newnode;
lp->size++;
}
void pop_front_list(list *lp)
{
if(lp->head==NULL)
{
printf("链表为空,删除失败。");
return;
}
Node *cur=lp->head;
lp->head=cur->next;
free(cur);
cur=NULL;
lp->size--;
}
void pop_back_list(list *lp)
{
if(lp->head==NULL)
{
printf("链表为空,删除失败");
return;
}
Node *cur=lp->head;
Node *pre=NULL;
if(cur->next==NULL)
{
lp->head=NULL;
free(cur);
cur=NULL;
lp->size--;
return;
}
while(cur->next)
{
pre=cur;
cur=cur->next;
}
pre->next=NULL;
free(cur);
cur=NULL;
lp->size--;
}
void destory_list(list *lp)
{
Node *cur=lp->head;
Node *pre=NULL;
while(cur)
{
pre=cur;
cur=cur->next;
free(pre);
}
pre=NULL;
lp->head =NULL;
lp->size=0;
}
void print_list(list *lp)
{
Node *cur=lp->head;
while(cur)
{
printf("%d->",cur->data );
cur=cur->next;
}
printf("NULL ");
printf("%d个节点\n",lp->size);
}
int main()
{
list lp;
init_list(&lp);
push_back_list(&lp,1);
print_list(&lp);
push_back_list(&lp,12);
print_list(&lp);
push_back_list(&lp,123);
print_list(&lp);
push_frout_list(&lp,4);
print_list(&lp);
push_frout_list(&lp,45);
print_list(&lp);
push_frout_list(&lp,456);
print_list(&lp);
pop_front_list(&lp);
print_list(&lp);
pop_back_list(&lp);
print_list(&lp);
destory_list(&lp);
print_list(&lp);
}