Linked_List 의 삽입과 삭제

Posted by MD워시퍼
2009. 7. 10. 18:46 Study
728x90

#include <stdio.h>
#include <stdlib.h>

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

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

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

    temp->key = count++;

 while(p->next != tail) {
  p = p->next;
 }

 temp->next = p->next;
    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;
    break;
   } else if(p->next == NULL){
    printf("데이터가 존재하지 않습니다");
    return;
   } else {
    p = p->next;
   }
  }
 }
 free(temp);
}

void main() {
    link_list *pointer;

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

    head->key = count++;
    tail->key = count++;
    head->next = tail;
    tail->next = NULL;

    insert_node();  // ①
    insert_node();  // ②
    insert_node();
    insert_node();
    delete_node(0);
    delete_node(3);

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