#include <stdio.h> #include "link.h" void print_item(link p) { printf("%d\n", p->item); } int main(void) { link head, tail, p; //struct node *head; link_init(&head, &tail); //head => NULL p = make_node(3); link_insert(&head, &tail, p); //头插法 p = make_node(5); link_insert(&head, &tail, p); //头插法 p = make_node(1); link_insert(&head, &tail, p); //头插法 p = make_node(8); link_insert(&head, &tail, p); //头插法 link_travel_head(&head, print_item); //遍历打印链表数值域 printf("***************\n"); link_travel_tail(&tail, print_item); //遍历打印链表数值域 printf("***************\n"); p = link_search(&head, 1); if (p != NULL) { link_delete(&head, &tail, p); free_node(p); } link_travel_tail(&tail, print_item); //遍历打印链表数值域 link_destory(&head, &tail); return 0; }
#ifndef _LINK_H_ #define _LINK_H_ typedef struct node *link; struct node { int item; link next; //struct node *next; 后继 link pre; //struct node *pre; 前驱 }; void link_init(link *head, link *tail); link make_node(int item); void link_insert(link *head, link *tail, link p); link link_search(link *head, int key); void link_delete(link *head, link *tail, link p); void free_node(link p); void link_modfie(link p, int key); void link_destory(link *head, link *tail); void link_travel_head(link *head, void (*vist)(link)); void link_travel_tail(link *tail, void (*vist)(link)); #endif
#include <stdio.h> #include <stdlib.h> #include "link.h" void link_init(link *head, link *tail) //struct node **head = &head { //head = NULL; *head = *tail = NULL; } link make_node(int item) { //link p = (link *)malloc(sizeof(struct node)); link p = (link)malloc(sizeof(*p)); p->item = item; //(*p).itme = item; p->next = NULL; //#define NULL (void *)0 p->pre = NULL; //#define NULL (void *)0 return p; } void link_insert(link *head, link *tail, link p) //头插法 { link q; if (*head == NULL) { *head = p; *tail = p; return; } p->next = *head; (*head)->pre = p; *head = p; } link link_search(link *head, int key) { link p; for (p = *head; p != NULL; p = p->next) if (p->item == key) return p; return NULL; } void link_delete(link *head, link *tail, link q) { link p; if (q == *head) { *head = q->next; (*head)->pre = NULL; return; } if (q == *tail) { *tail = q->pre; (*tail)->next = NULL; return; } q->pre->next = q->next; q->next->pre = q->pre; } void free_node(link p) { free(p); } void link_modfie(link p, int key) { p->item = key; } void link_destory(link *head, link *tail) { link p= *head, q; while (p != NULL) { q = p->next; free(p); p = q; } *head = NULL; *tail = NULL; } void link_travel_head(link *head, void (*vist)(link)) { link p; for (p = *head; p != NULL; p = p->next) vist(p); } void link_travel_tail(link *tail, void (*vist)(link)) { link p; for (p = *tail; p != NULL; p = p->pre) vist(p); }
时间: 2024-10-26 11:09:33