공부도 할겸 C언어로 연결리스트 구현.... 그냥 입력은 맨 처음에 넣는 방법으로 했고... 간단하게 구현해서 코드 읽기도 어렵지 않고, 어떻게 생각하면 부족한 부분이 많은 코드...
연결 리스트 : 일정한 순설르 가지는 데이터 항목들을 표현한느 방법중 하나. 배열과 같은 순차적 표현방법과 달리 데이터 항목의 논리적인 순서만 유지되고 기억장소 내에서는 각 항목들의 임의의 위치를 가지도록 하는 자료구조.
#include <stdio.h> #include <stdlib.h> struct Node { int data; Node* next; }; void isnert_node(Node* node, int input_data) { Node* newNode = (Node *)malloc(sizeof(Node)); newNode->data = input_data; if(node->next == NULL) newNode->next = NULL; else newNode->next = node->next; node->next = newNode; } void delete_node(Node* node, int delete_data) { Node* tmp = (Node* )malloc(sizeof(Node)); Node* tmp_prev = (Node*) malloc(sizeof(Node)); tmp = node; tmp_prev = node; if(tmp->next == NULL) { printf("no value "); return ; } while(1) { if(tmp->next == NULL) { printf("no search "); return; } tmp_prev = tmp; tmp = tmp->next; if(tmp->data == delete_data) { tmp_prev->next = tmp->next; free(tmp); return ; } } } void display_node(Node* node) { Node *tmp = node; printf("[start]"); while(tmp != NULL) { printf(" -> [%d]", tmp->data); tmp = tmp->next; } } int main() { Node* head = (Node* ) malloc(sizeof(Node)); head->data = 0; head->next = NULL; int in; char _input; while(1) { printf("[(i)nsert, (d)elete, (p)rint, (q)uit] : "); scanf("%c", &_input); getchar(); // 엔터 입력 if(_input == 'i') { printf("input number : "); scanf("%d", &in); getchar(); isnert_node(head, in); } else if(_input == 'd') { printf("delete number : "); scanf("%d", &in); getchar(); delete_node(head, in); } else if(_input == 'p') display_node(head->next); else if(_input == 'q') break; else printf("Invalid input.. "); printf(" "); } fflush(stdin); free(head); return 0; }
'STUDY > C++' 카테고리의 다른 글
[ STL : User Define Allocator - Nicolai M. Josuttis ] (0) | 2014.08.07 |
---|---|
[C] Linked-List 링크리스트 구현 (연결리스트) 소스 (0) | 2013.08.20 |
C++ 상속 부모클래스 있을때 생성자 순서 (0) | 2013.08.20 |
const_cast static_cast reinterpret_cast dynamic_cast 형변환 (0) | 2013.08.19 |
[C++] Linked-List 링크리스트 구현 (연결리스트) 소스 (0) | 2013.04.18 |
[C++] Binary Search & Sequential Search 구현 (이원탐색 || 이진탐색 및 순차탐색) 소스 (0) | 2013.04.18 |