C 자료구조와 알고리즘

이중 연결리스트

june__Park 2021. 6. 29. 19:02
// 이중연결리스트

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

typedef struct node{
	int data;
	struct node* prev;
	struct node* next;
} NODE;

NODE* init(int data){
	NODE* tmp = (NODE*)malloc(sizeof(NODE));
	tmp->data = data;
	tmp->prev = NULL;
	tmp->next = NULL;
	return tmp;
}
void print_all(NODE* head){
	NODE* tmp = head;
	while(tmp){
		printf("%d ", tmp->data);
		tmp = tmp->next;
	}
	printf("\n");
}

void print_all_reverse(NODE* tail){
	NODE* tmp = tail;
	while(tmp){
		printf("%d ", tmp->data);
		tmp = tmp->prev;
	}
	printf("\n");
}

void add(NODE** h, NODE** t, int data){
	NODE* head = *h;
	NODE* tail = *t;
	NODE* tmp = init(data);
	tmp->prev = tail;
	*t = tmp;
	if(tail)
		tail->next = tmp;
	if(!head){
		*h = tmp;
	}
}



void add(NODE** p, int data){
	if(!*p) {  // *p == NULL
		*p = init(data);
		return;
	}
	add(&(*p)->next, data);
}

void main(){
	NODE *head = NULL, *tail = NULL;
	int select = 0;
	while(1){
		print_all(head);
		print_all_reverse(tail);
		printf("정수(종료 -1) : ");
		scanf_s("%d", &select);
		if(select == -1){ break; }
		add(&head, &tail, select); // 리스트의 가장 마지막에 새노드를 추가하는 add() 구현
		system("pause");
		system("cls");
	}
}