list.h
#ifndef __LIST_H
#define __LIST_H
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
typedef struct node
{
int data;
struct node *next;
}node_t;
typedef struct list
{
struct node* head;
struct node* tail;
}list_t;
extern struct node *creat_node(int data);
extern void print_list(list_t *list);
extern void add_node(list_t *list,int data);
extern void add_node_head(list_t* list,int data);
extern void add_node_tail(list_t *list,int data);
extern void node_del(list_t *list ,int data);
extern void init_list(list_t *list);
extern void desinit_list(list_t *list);
#endif
list.c
#include"list.h"
struct node *creat_node(int data)
{
node_t *new_node = (node_t *)malloc(sizeof(node_t));
new_node->data = data;
new_node->next = NULL;
return new_node;
}
void print_list(list_t *list)
{
for (node_t *pnode= list->head;pnode != list->tail;pnode = pnode->next)
{
node_t *pfirst = pnode;
node_t *pmid = pfirst->next;
node_t *plast = pmid->next;
if(pmid != list->tail)
{
printf("%d ",pmid->data);
}
}
printf("\n");
}
void add_node(list_t *list,int data)
{
node_t *new_node =creat_node(data);
for (node_t *pnode= list->head;pnode != list->tail;pnode = pnode->next)
{
node_t *pfirst = pnode;
node_t *pmid = pfirst->next;
node_t *plast = pmid->next;
if(pmid->data >= new_node->data || pmid == list->tail)
{
pfirst->next = new_node;
new_node->next = pmid;
break;
}
}
}
void add_node_head(list_t* list,int data)
{
node_t *new_node = creat_node(data);
new_node->next = list->head->next;
list->head->next = new_node;
}
void add_node_tail(list_t *list,int data)
{
node_t *new_node = creat_node(data);
for (node_t *pnode= list->head;pnode != list->tail;pnode = pnode->next)
{
node_t *pfirst = pnode;
node_t *pmid = pfirst->next;
node_t *plast = pmid->next;
if(plast ==list->tail)
{
new_node->next = plast;
pmid->next = new_node;
break;
}
}
}
void node_del(list_t *list ,int data)
{
for (node_t *pnode= list->head;pnode != list->tail;pnode = pnode->next)
{
node_t *pfirst = pnode;
node_t *pmid = pfirst->next;
node_t *plast = pmid->next;
if(pmid->data == data && pmid != list->tail)
{
pfirst->next = plast;
break;
}
}
}
void init_list(list_t *list)
{
list->head= creat_node(0);
list->tail= creat_node(0);
list->head->next = list->tail;
list->tail->next = NULL;
}
void desinit_list(list_t *list)
{
node_t *pnode = list->head;
while(pnode!=list->tail)
{
node_t * ptmp = pnode->next;
free(pnode);
pnode = ptmp;
}
}
list_main.c
#include"list.h"
int main(void)
{
list_t list;
init_list(&list);
add_node(&list,10);
add_node(&list,20);
add_node(&list,30);
print_list(&list);
add_node(&list,18);
print_list(&list);
add_node_head(&list,77);
add_node_head(&list,15);
add_node_tail(&list,66);
print_list(&list);
node_del(&list,20);
print_list(&list);
desinit_list(&list);
init_list(&list);
print_list(&list);
return 0;
}
Makefile
BIN = list
OBJ = list.c
OBJ += list_main.c
list:list.c list_main.c
gcc $(OBJ) -o $(BIN)
clean:
rm $(BIN)
运行结果: