单向链表带头节点(head)(数据域,指针域)
随机访问性比较差 但是插入删除操作较为简单。
list.h
#ifndef LIST_H__
#define LIST_H__typedef int datatype;typedef struct node_st
{datatype data;struct node_st *next;
}link;link *list_create();int list_insert_at(link *,int i,datatype *);
int list_order_insert(list *,datatype *);int list_delete_at(list *,int i,datatype *);
int list_delete(list *,datatype *);int list_isempty(list *);
void list_display(list *);
void list_destory(list *);#endif
list.c
#include<stdio.h>
#include<stdlib.h>#include"list.h"link *list_create()
{list *me;me = malloc(sizeof(*me));if(me=NULL)return NULL;me->data = NULL;return me;
}
int list_insert_at(link *me,int i,datatype *data)
{int j = 0;list *node = me;list *newnode;if(i<0)return 0;while(j < i && node != null){node = node->next;j++;}if(node){newnode = malloc(sizeof(*newnode));if(newnode == NULL)return -2;newnode->data = *data;//newnode->data = NULL;newnode->next = node->next;node->next = newnode;return 0;}else return -3;
}
int list_order_insert(list *me,datatype *data)
{list *p = me,*q;while(p->next && p->next->data < *data)p = p->next;q = malloc(sizeof(*q));if(q = NULL)return -1;q->data = *data;q->next = p->next;p->next = q;return 0;}
int list_delete_at(list *me,int i,datatype *data)
{int j =0;list *p =me,*q;if(i<0)return -1;*data = -1;while(j < i){p = p->next;j++;}if(p){q= p->next;p->next = q->next;*data = q->data;free(q); q= NULL;return 0;}elsereturn -2;
}
int list_delete(list *me,datatype *data)
{list *p = me,*q;while(p->next && p->next->data != *data)p = p->next;if(p->next == NULL)return -1;else{q = p->next;p->next = q->next;free(q);q = NULL;} }
int list_isempty(list *me)
{if(me->next == NULL)return 0;return 1;
}
void list_display(list *me)
{list *node = me->next;if(list_isempty(me)==0)return ;while(node !==NULL){printf("%d ",node->data);node = node->next;}printf("\n");return ;
}
void list_destory(list *me)
{list *node,*next;for(node = me->next;node != NULL;node = next){next = node->next;free(node);}free(me);return ;
}
main.c
#include<stdio.h>
#include<stdlib.h>#include"list.h"int main()
{datatype arr[] = {12,9,23,2,34,6,45};list *l;int i;l = list_create();if(l == NULL)exit(1);for(i = 0;i<sizeof(arr)/sizeof(*arr);i++){if(list_order_insert(l,&arr[i]))//if(list_insert_at(l,0,&arr[i]))exit(1);}list_display(l);//int value = 12;//list_delete(l,&value);//list_display(l);int err;datatype value;err = list_delete_at(l,2,&value);if(err)exit(1);list_display(l);printf("delete:%d\n",value);list_destroy(l);exit(0);
}
makefile
all:mainmain:main.o list.o$(CC) $^ -o $@clean:rm *.o main -rf