//Double Linked List
#include<stdio.h>
#include<stdlib.h>
typedef struct _node
{
int data;
struct _node* back;
struct _node* next;
}node;
node *head, *tail;
void print_all(void);
void init_link(void);
void insert_link(int x);
node* find_node(int x);
void insert_before(int x, node* y);
void del_node(node* x);
void all_del_node(void);
void main()
{
init_link();
insert_link(10);
insert_link(5);
insert_link(8);
insert_link(3);
insert_link(1);
insert_link(7);
insert_link(8);
printf("Inital Linked list is ");
print_all();
printf("Finding 4 is %s\n", find_node(4) != tail ? "successful" : "unsuccessful");
printf("Finding 5 is %s\n", find_node(5) != tail ? "successful" : "unsuccessful");
puts("Inserting 7 before 5");
insert_before(7, find_node(5));
print_all();
puts("Deleting 3");
del_node(find_node(3));
print_all();
puts("Inserting node 2 before 10");
insert_before(2, find_node(10));
print_all();
puts("Deleting 2");
del_node(find_node(2));
print_all();
puts("Deleting 1");
del_node(find_node(1));
print_all();
puts("Insering node 15");
insert_before(15, head->next);
print_all();
puts("Deleting all node");
all_del_node();
print_all();
}
//전체 노드 삭제
void all_del_node(void)
{
node* temp;
temp = head->next;
while(temp != tail)
{
temp = temp->next;
free(temp->back);
}
//노드 초기화
head->next = tail;
tail->back = head;
}
//노드를 입력받아 삭제
void del_node(node* x)
{
if(x != tail)
{
x->back->next = x->next;
x->next->back = x->back;
free(x);
}
else
puts("!!!!!!!!!!!!!!!!! Not Node !!!!!!!!!!!!!!!!!");
}
//찾은 노드 이전에 삽입
void insert_before(int x, node* y)
{
node* temp = (node*)malloc(sizeof(node));
temp->data = x;
y->back->next = temp;
temp->back = y->back;
y->back = temp;
temp->next = y;
}
//노드 찾기
node* find_node(int x)
{
node* temp;
temp = head->next;
while(temp->data != x && temp != tail)
temp = temp->next;
return temp;
}
//노드값 화면에 출력
void print_all(void)
{
node* temp;
temp = head->next;
while(temp != tail)
{
printf("%5d",temp->data);
temp = temp->next;
}
printf("\n");
}
//노드 초기화
void init_link(void)
{
head = (node*)malloc(sizeof(node));
tail = (node*)malloc(sizeof(node));
head->next = tail;
head->back = head;
tail->next = tail;
tail->back = head;
}
//노드 입력 받기
void insert_link(int x)
{
node *a;
node* temp = (node*)malloc(sizeof(node));
a = head->next;
while(a->data <= x && a != tail)
a = a->next;
temp->data = x;
a->back->next = temp;
temp->back = a->back;
temp->next = a;
a->back = temp;
}