티스토리 뷰
1. 링크드 리스트 스택.
1. 링크드 리스트 스택 클래스.
#include "20160322.h" #ifdef CPP using namespace std; #endif void CreateStack(Stack** _Stack) { #ifdef CPP (*_Stack) = new Stack; #else (*_Stack) = (Stack*)malloc(sizeof(Stack)); #endif (*_Stack)->List = NULL; (*_Stack)->Top = NULL; } void DestroyStack(Stack* _Stack) { while(!IsEmpty(_Stack)) { Node* Current = Pop(_Stack); DestroyNode(Current); } } Node* CreateNode(ElementType NewData) { #ifdef CPP Node* NewNode = new Node; NewNode->Data = NewData; #else Node* NewNode = (Node*)malloc(sizeof(Node)); NewNode->Data = (ElementType)malloc(strlen(NewData) + 1); strcpy_s(NewNode->Data, strlen(NewData) + 1, NewData); #endif NewNode->NextNode = NULL; return NewNode; } void DestroyNode(Node* Node) { #ifdef CPP delete Node; Node = NULL; #else free(Node->Data); Node->Data = NULL; free(Node); Node = NULL; #endif } void Push(Stack* _Stack, Node* NewNode) { if (NULL == _Stack->List) _Stack->List = NewNode; else { Node* Temp = _Stack->List; while (NULL != Temp->NextNode) Temp = Temp->NextNode; Temp->NextNode = NewNode; } _Stack->Top = NewNode; } Node* Pop(Stack* _Stack) { Node* TopNode = _Stack->Top; if (_Stack->List == _Stack->Top) { _Stack->List = NULL; _Stack->Top = NULL; } else { Node* Current = _Stack->List; while(NULL != Current && _Stack->Top != Current->NextNode) Current = Current->NextNode; _Stack->Top = Current; Current->NextNode = NULL; } return TopNode; } Node* Top(Stack* _Stack) { return _Stack->Top; } int GetSize(Stack* _Stack) { int nCount = 0; Node* Current = _Stack->List; while(NULL != Current) { Current = Current->NextNode; nCount++; } return nCount; } int IsEmpty(Stack* _Stack) { return (NULL == _Stack->List); }
2. 메인 클래스.
#include "20160322.h" #ifdef CPP using namespace std; #endif void main(void) { Stack* tStack; CreateStack(&tStack); //Push(tStack, CreateNode("aaa")); //Push(tStack, CreateNode("bbb")); //Push(tStack, CreateNode("ccc")); //Push(tStack, CreateNode("ddd")); Push(tStack, CreateNode(1)); Push(tStack, CreateNode(2)); Push(tStack, CreateNode(3)); Push(tStack, CreateNode(4)); int nCount = GetSize(tStack); #ifdef CPP cout << "Size : " << nCount << ", Top : " << Top(tStack)->Data << endl; #else printf("Size : %d, Top : %s\n", nCount, Top(tStack)->Data); #endif Node* tNode; for (int i = 0; i < nCount; ++i) { if (IsEmpty(tStack)) break; tNode = Pop(tStack); #ifdef CPP cout << "Pop : " << tNode->Data << ", "; #else printf("Pop : %s, ", tNode->Data); #endif DestroyNode(tNode); if (!IsEmpty(tStack)) { #ifdef CPP cout << "Current Top : " << Top(tStack)->Data << endl; #else printf("Current Top : %s\n", Top(tStack)->Data); #endif } else { #ifdef CPP cout << "Stack is Empty." << endl; #else printf("Stack is Empty\n"); #endif } } DestroyStack(tStack); }
'뇌를 자극하는 알고리즘' 카테고리의 다른 글
2016/03/23 (0) | 2016.03.23 |
---|---|
2016/03/21 (0) | 2016.03.21 |
댓글
공지사항