c语言实现有头单向链表
#include <stdio.h> #include<stdlib.h> #include<string.h> //采用有头链表,头节点不存数据,所以数据操作都从头节点所指的下一节点开始,这样就不会误操作到头节点。 typedef int data_t; typedef struct linklist { data_t data; struct linklist *next; }LinkList; //创建头节点 LinkList * create_linklist(){ LinkList *head = (LinkList *)malloc(sizeof(LinkList)); if(NULL == head){ printf("malloc failed\n"); return NULL; } head->data = 0; head->next = NULL; return head; } //判断是否为空 int is_empty(LinkList *head){ if(head->next == NULL) return 0; else return 1; } int len_of_linklist(LinkList *head){ int cnt=0; if(head->next == NULL){ return cnt; } while(head->next){ cnt++; head=head->next; } return cnt; } //头插法添加数据,从头结点后添加结点存储数据 void head_add_list(LinkList *head,data_t data) { LinkList *new = (LinkList *)malloc(sizeof(LinkList)); if(NULL == new){ printf("malloc failed\n"); } new->data = data; new->next = head->next; head->next = new; } //按位置插入 void pos_add_list(LinkList *head,int pos,data_t data) { LinkList *new = (LinkList *)malloc(sizeof(LinkList)); if(NULL == new){ printf("malloc failed\n"); } LinkList *p=head; if(pos<0 || pos > len_of_linklist(head)) return ; while(pos--){ p=p->next; } new->data = data; new->next = p->next; p->next = new; } void pos_del_list(LinkList *head,int pos) { LinkList *p = head; while(pos--){ p=p->next; } LinkList *q=p->next; p->next = p->next->next; free(q); q=NULL; } void printf_list(LinkList * head) { if(head == NULL){ return ; } LinkList *p = head->next; while (p != NULL) { printf("list=%d\n",p->data); p=p->next; } } void list_dele(LinkList *head) { LinkList *p=head->next; int pos = len_of_linklist(head); while(pos-- && pos>=0){ pos_del_list(head,pos); } return; } //销毁链表 void destory_list(LinkList ** head){ //清除头指针 if(is_empty(*head) == 0){ free(*head); *head=NULL; }else printf("链表不为空,长度为=%d\n",len_of_linklist(*head)); } int main(int argc, char const *argv[]) { LinkList *head=create_linklist(); //head_add_list(head,5); head_add_list(head,4); head_add_list(head,3); head_add_list(head,2); head_add_list(head,1); printf_list(head); list_dele(head); destory_list(&head); printf_list(head); return 0; }