-
문제 06-1 연결 리스트를 이용한 스택의 또 다른 구현Data Structure/윤성우의 열혈 자료구조 2019. 7. 7. 04:00
문제 : 원형 연결리스트를 이용해서 스택을 구현해보자.
// CLInkedList. h
#include <stdio.h>
#include <stdlib.h>
typedef struct _node
{
int data;
struct _node * next;
}Node;
typedef struct _list
{
Node * head;
Node * tail;
Node * before;
Node * cur;
int numOfdata;
}List;
void InitList(List * plist)
{
plist->tail = NULL;
plist->numOfdata = 0;
}
void LInsert(List * plist, int data)
{
Node * newnode = (Node*)malloc(sizeof(Node));
newnode->data = data;
if (plist->tail == NULL)
{
plist->tail = newnode;
newnode->next = newnode;
}
else
{
newnode->next = plist->tail->next;
plist->tail->next = newnode;
plist->tail = newnode;
}
(plist->numOfdata)++;
}
void LInsertFront(List * plist, int data)
{
Node * newnode = (Node*)malloc(sizeof(Node));
newnode->data = data;
if (plist->tail == NULL)
{
plist->tail = newnode;
newnode->next = newnode;
}
else
{
newnode->next = plist->tail->next;
plist->tail->next = newnode;
}
(plist->numOfdata)++;
}
int LFirst(List * plist, int * data)
{
if (plist->tail == NULL)
return 0;
plist->cur = plist->tail->next;
plist->before = plist->tail;
*data = plist->cur->data;
return 1;
}
int LNext(List * plist, int * data)
{
if (plist->tail == NULL)
return 0;
plist->before = plist->cur;
plist->cur = plist->cur->next;
*data = plist->cur->data;
return 1;
}
int LRemove(List * plist)
{
Node * rpos = plist->cur;
int temp = plist->cur->data;
if (rpos == plist->tail)
{
if (plist->tail == plist->tail->next)
plist->tail = NULL;
else
plist->tail = plist->before;
}
plist->before->next = plist->cur->next;
plist->cur = plist->before;
free(rpos);
(plist->numOfdata)--;
return temp;
}
int LCount(List * plist)
{
return plist->numOfdata;
}
// CLLBaseStack.h
#include <stdio.h>
#include <stdlib.h>
#include "CLinkedList.h"
typedef struct _listtack
{
List * plist;
}Stack;
void StackInit(Stack * pstack)
{
pstack->plist = (List*)malloc(sizeof(List));
InitList(pstack->plist);
}
int SIsEmpty(Stack * pstack)
{
if (LCount(pstack->plist) == 0)
return 1;
else
return 0;
}
void SPush(Stack * pstack, int data)
{
LInsertFront(pstack->plist, data);
}
int SPop(Stack * pstack)
{
int data;
LFirst(pstack->plist, &data);
LRemove(pstack->plist);
return data;
}
int SPeek(Stack * pstack)
{
int data;
LFirst(pstack->plist, &data);
return data;
}
// Main. c#include <stdio.h>#include "CLLBaseStack.h"int main(){Stack stack;StackInit(&stack);SPush(&stack, 1);SPush(&stack, 2);SPush(&stack, 3); // 1 2 3 순으로 들어갔음으로 FILO인 스택은 3 2 1 순으로 나와야함while (!SIsEmpty(&stack))printf("%d", SPop(&stack));return 0;}'Data Structure > 윤성우의 열혈 자료구조' 카테고리의 다른 글
문제 03 -1 리스트 라이브러리의 활용 (0) 2019.09.04 문제 11-1 이진 탐색 트리의 조건 (0) 2019.08.16 문제 09 -1 우선순위 큐의 활용 (0) 2019.07.29 문제 08-1 이진 트리의 소멸 (0) 2019.07.15 문제05-2 더미 노드 기반의 양방향 연결 리스트 구현 (0) 2019.07.02