数据结构基础(1)-->双向链表

来源:互联网 发布:python粒子群算法 编辑:程序博客网 时间:2024/06/05 14:38
linklist.h
#ifndefLINK_LIST_H#defineLINK_LIST_H1#include <stdio.h>#include <string.h>#include <malloc.h>struct stu{charname[32];charstu_num[32];charsex[16];intage;structstu*next;structstu*pre;};struct stu *initlist(struct stu **head);void destroylist(struct stu *head);void clearlist(struct stu *head);int listempty(const struct stu *head);int listlength(const struct stu *head);struct stu *getelem(const struct stu *head, int i);void listinsert(struct stu *head, struct stu *new);void listdelete(struct stu *node);#endif /* LINK_LIST_H */

linklist.c
#include <linklist.h>struct stu *initlist(struct stu **head){*head = (struct stu *)malloc(sizeof(struct stu));if(!*head) {return NULL;}memset(*head, 0, sizeof(struct stu));(*head)->next = *head;(*head)->pre = *head;return *head;}void destroylist(struct stu *head){clearlist(head);free(head);return;}void clearlist(struct stu *head){struct stu *n;for(n=head->next; head->next!=head; n=head->next) {head->next = n->next;n->next->pre = head;free(n);}return;}int listempty(const struct stu *head){return head->next == head;}int listlength(const struct stu *head){int i = 0;struct stu *n = head->next;while(n != head) {n = n->next;++i;}return i;}struct stu *getelem(const struct stu *head, int i){struct stu *n = (struct stu *)head;for(; i--&&((n=n->next)!=head);)/* nothing*/;return n==head ? NULL:n;}void listinsert(struct stu *head, struct stu *new){new->next = head;new->pre = head->pre;head->pre->next = new;head->pre = new;return;}void listdelete(struct stu *node){node->pre->next = node->next;node->next->pre = node->pre;free(node);return;}