Double Linked List

Posted by MD워시퍼
2009. 7. 14. 10:01 Study
728x90
#include <stdio.h>
#include <stdlib.h>

typedef struct link {
    int key;
    struct link *next;
    struct link *pre;
} link_list;

link_list *head;
link_list *tail;

void insert_node(int count) {
    link_list *temp, *p = head;

    temp = (link_list *)malloc(sizeof(link_list));

    temp->key = count;

    while(p->next != tail && p->next->key < count) {
        p = p->next;
    }

    temp->next = p->next;
    temp->pre = p->next->pre;
    p->next->pre = temp;
    p->next = temp;


}

void delete_node(int key) {
 link_list *temp, *p;

 p = head;

 if(head->key == key) {
  temp = head;
  head = head->next;
 } else {
  while(true) {
   if(p->next->key == key) {
    temp = p->next;
    p->next = p->next->next;
    p->next->pre = p->next->pre->pre;
    break;
   } else if(p->next == NULL){
    printf("데이터가 존재하지 않습니다");
    return;
   } else {
    p = p->next;
   }
  }
 }
 free(temp);
}

void main() {
    int count;
    link_list *p;

    head = (link_list *)malloc(sizeof(link_list));
    tail = (link_list *)malloc(sizeof(link_list));

    head->next = tail;
    head->pre = NULL;
    tail->next = NULL;
    tail->pre = head;
    p = head;
   
    for(int i = 0 ; i < 50 ; i++) {
        count = (int)(rand()%100);
        insert_node(i);  // ①
    }
    delete_node(11);
    do {
        p = p->next;
        printf("%d ",p->key);
    }while(p->next != tail);

    do {
        p = p->pre;
        printf("%d ",p->key);
    }while(p->pre != head);

    printf("\n");
}