c 언어 플러그인 간단한 체인 테이블 쓰기

#include 
#include   // exit         

typedef struct node   //       ,        item,    next
{
    int item;
    struct node *next;
}node;

node *head = NULL;    //       ,      

node *mk_node(int item)  //    ,         
{
    node *p = (node *)malloc(sizeof(node)); // malloc    
    if (p == NULL)    //        
    {
        printf("malloc fail");
        exit(1);
    }
    p->item = item;
    p->next = NULL;
    return p;
}

void free_node(node *p) //    
{
    free(p);
}

void insert_node(node *p)  //    
{
    p->next = head;
    head = p;
}

void print_node(node *p)  //    
{
    printf("%d ", p->item);
}

void traverse()  //   
{
    node *p = head;
    while (p != NULL)
    {
        print_node(p);
        p = p->next;
    }
    printf("
"); } node *search_node(int item) // { node *p = head; while (p != NULL) { if (p->item == item) { return p; } p = p->next; } return NULL; } void rm_node(node *p) // { node *pre = head; if (head == p) // , , , { head = head->next; p = NULL; } while (pre->next != NULL) { if (pre->next == p) { pre->next = p->next; // return; } pre = pre->next; } } void distory() // { while (head != NULL) { node *pre = head; head = head->next; free_node(pre); } } int main() { int target; // node *p = mk_node(1); insert_node(p); p = mk_node(2); insert_node(p); p = mk_node(3); insert_node(p); p = mk_node(4); insert_node(p); p = mk_node(5); insert_node(p); p = mk_node(6); insert_node(p); p = mk_node(7); insert_node(p); p = mk_node(8); insert_node(p); traverse(); printf(" :
"); scanf("%d", &target); p = search_node(target); if (p != NULL) { printf("%p %d %d
", p, p->item, target); rm_node(p);// traverse(); }else { printf("Can't find!"); } distory(); traverse(); return 0; }

좋은 웹페이지 즐겨찾기