Owl Life

자료구조_Double Linked List (DLL) 본문

자료구조_알고리즘

자료구조_Double Linked List (DLL)

Owl Life 2018. 5. 11. 22:05
반응형

Double Linked List 소스코드입니다.



#include "iostream"
using namespace std;

#define MAX_NODE 100

typedef int DATA;
typedef struct _node {
	DATA data;
	struct _node *prev;
	struct _node *next;	
} NODE;
NODE node_list[MAX_NODE + 1];
int node_list_idx;

NODE *head, *tail;

void init() {
	node_list_idx = 0;
	head = 0;
	tail = 0;
}

NODE *alloc_node(DATA data) {
	NODE* node = &node_list[node_list_idx++];
	node->data = data;
	return node;
}

void add_to_first(DATA data) {
	NODE *node = alloc_node(data);
	node->next = head;
	if (head != 0) {
		head->prev = node;
	}
	head = node;

	if (head->next == 0) {
		tail = head;
	}
}

void add_to_last(DATA data) {
	NODE *node = alloc_node(data);
	if (head == 0) {
		add_to_first(data);
		return;
	}

	tail->next = node;
	node->prev = tail;
	tail = node;
}

void remove_first_node() {
	if (head == 0) {
		return;
	}
	head = head->next;
}

void remove_last_node() {
	if (tail == 0) {
		return;
	}
	tail = tail->prev;
	tail->next = 0;
}

void remove_data(DATA data) {
	NODE *target_node = 0;
	for (target_node = head; target_node != 0; target_node = target_node->next) {
		if (target_node->data == data) {
			break;
		}
	}
	if (target_node == 0) {
		cout << "Failed to find a data : " << data << endl;
		return;
	}

	if (head == target_node) {
		head = target_node->next;
		return;
	}

	if (tail == target_node) {
		tail = target_node->prev;
		tail->next = 0;
		return;
	}

	target_node->prev->next = target_node->next;
	target_node->next->prev = target_node->prev;
}

void clear() {
	head = tail = 0;
}

void disp_all_data() {
	for (NODE* node = head; node != 0; node = node->next) {
		cout << node->data << " -> ";
	}
	cout << endl;
}

int main() {
	add_to_last(1);
	add_to_first(10);
	add_to_first(12);
	add_to_first(20);
	disp_all_data(); // 20 -> 12 -> 10 -> 1

	remove_data(1);
	remove_data(12);
	disp_all_data(); // 20 -> 10 ->

	add_to_last(9); // 20 -> 10 -> 9
	remove_first_node();
	remove_last_node();
	disp_all_data(); // 10

	clear();
	disp_all_data(); //

	return 0;
}

반응형

'자료구조_알고리즘' 카테고리의 다른 글

덱(deque) 자료구조  (0) 2018.06.07
자료구조_Binary Search Tree (BST)  (0) 2018.05.11
Comments