700 likes | 894 Views
Chapter 3. Stacks. Internet Computing Laboratory @ KUT Youn-Hee Han. 0. Stack Concept. Linear List In a linear list, each element has a unique successor Linear List Categories. Element 1. Element 1. Element 1. Element 1. Linear List. Restricted. General Chapter 5. Stack Chapter 3.
E N D
Chapter 3. Stacks Internet Computing Laboratory @ KUT Youn-Hee Han
0. Stack Concept • Linear List • In a linear list, each element has a unique successor • Linear List Categories Element 1 Element 1 Element 1 Element 1 Linear List Restricted General Chapter 5 Stack Chapter 3 Queue Chapter 4 Data Structure
0. Stack Concept • Stack (스택) • 들어온 시간 순으로 데이터를 쌓아갈 때 가장 위에 즉, 가장 최근에 삽입된 위치에 있는 데이터를 삭제하거나 아니면 거기에 이어서 새로운 데이터를 삽입할 수 있도록 하는 추상 자료형 • A data structure, in which you can add or delete from only one side Data Structure
0. Stack Concept • Stacks in Daily Lives • Coin case • Terrible parking lot Data Structure
C A B A B C D A B C A B C 0. Stack Concept • Stack (스택) 후입선출(後入先出) • LIFO(Last-In, First-Out: 라이포 또는 리포) • LCFS(Last-Come, First-Served) • cf. 큐: 선입선출(先入先出), FIFO(First-In, First-Out: 파이포 또는 피포) Data Structure
C push(A) push(B) push(C) pop() B B B A A A A 0. Stack Concept • 한쪽 끝에서 삽입, 삭제 • 삽입 삭제 위치를 Stack Top 위치로 제한함 • Implementation에서 Top 이 아닌 다른 곳을 접근할 수 있어도 하지 않기로 약속 초기상태 Data Structure
delete insert 0. Stack Concept • Stack: a linear list in which all additions and deletions are restricted to one end, called top • Given a stack S = (a0, a1, … , an-1), a0 is the bottom element and an-1 is the top element a0 a1 a2 … an-1 < ordered list > closed open insert a0 a1 a2 … an-1 delete Data Structure
1. Basic Stack Operations • Basic stack operations • CreateStack: allocate memory and initialize • Push • Pop • Stack Top • DestroyStack: remove all items and deallocate memory • Additional operations • IsFullStack : check if stack is full • IsEmptyStack : check if stack is empty • CountStackItem : returns # of items in a stack • ClearStack : removes all items in a stack Data Structure
1. Basic Stack Operations • Axiom (S is a stack, X is a data item) • Stack Top(Push(S, X)) = X • Pop(Push(S, X)) = S • IsEmptyStack(CreateStack( )) = TRUE • IsEmptyStack(Push(S, X)) = FALSE • CountStackItem(Push(S, X)) = CountStackItem (S) + 1 Data Structure
1. Basic Stack Operations • Push: adds an item at the top of the stack • New item becomes top Note! Before push an item, we should check if stack is full. Otherwise stack overflow can occur. Data Structure
1. Basic Stack Operations • Pop: remove the item at the top of the stack and return it • Next older item becomes top Note! Before pop an item, we should check if stack is empty. Otherwise stack underflow can occur. Data Structure
1. Basic Stack Operations • Stack Top: return the item at the top of the stack • Top element is not deleted Data Structure
1. Basic Stack Operations • Example of Stack Operation • Push(green) • Push(blue) • Pop() • Push(red) Data Structure
1. Basic Stack Operations • Example of Stack Operation • Stack Top() • Pop() • Pop() Data Structure
2. Stack Linked List Implementation • Data Structure • Head structure • Contain metadata, data about data • Two attributes • A top pointer • A count of the number of elements in the stack • Possible attributes • The time when the stack was created • The total number of items that have ever been placed in the stack • The average number of items processed through the stack in a given period Data Structure
2. Stack Linked List Implementation • Data Structure • C code stack count top end stack //head node data link end node count top Stack head structure data link Stack node structure typedef struct node { void* dataPtr; struct node* link; } STACK_NODE; typedef struct { int count STACK_NODE* top; } STACK; // Head Data Structure
2. Stack Linked List Implementation • Stack Operations • Create Stack Algorithm createStack 1. allocate memory for stack head 2. set count to 0 3. set top to null 4. return stack head end createStack Data Structure
2. Stack Linked List Implementation • Stack Operations • Push Algorithm pushStack (stack, data) 1. allocate new node 2. store data in new node 3. make current top node the second node 4. make new node the top 5. increment stack count end pushStack Data Structure
2. Stack Linked List Implementation • Stack Operations • Pop Algorithm popStack (stack, dataOut) 1. if (stack empty) 1. set success to false 2. else 1. set dataOut to data in the top node 2. make second node the top node 3. decrement stack count 4. set success to true 3. end if 4. return success end popStack Data Structure
2. Stack Linked List Implementation • Stack Operations • Stack Top • IsEmptyStack Algorithm stackTop (stack, dataOut) 1. if (stack empty) 1. set success to false 2. else 1. set dataOut to data in the top node 2. set success to true 3. end if 4. return success end stackTop Algorithm IsEmptyStack (stack) 1. if (stack count is 0) 1. return true 2. else 1. return false end IsEmptyStack Data Structure
2. Stack Linked List Implementation • Stack Operations • IsFullStack • CountStackItem Algorithm IsFullStack (stack) 1. if (memory not available) 1. return true 2. else 1. return false 3. end if 4. return success end IsFullStack Algorithm CountStackItem (stack) 1. return stack count end CountStackItem Data Structure
2. Stack Linked List Implementation • Stack Operations • DestroyStack Algorithm DestroyStack (stack) 1. if (stack not empty) 1. loop (stack not empty) 1. delete (pop) top node 2. end loop 2. end if 4. delete stack head end DestroyStack Data Structure
3. C Language Implementation • How about this? Push(stack, item)의동작방식 int main() { int i = 0; int item = 0; // variables for stack int stack[100]; // CreateStack int top = -1; printf("Input 10 numbers :"); for(i = 0; i < 10; i++){ item = 0; scanf("%d", &item); stack[++top] = item; // Push(stack, item); } printf("Reversed :"); while(top >= 0){ item = stack[top--]; // item = Pop(stack); printf("%d ", item); } printf("\n"); return 0; } Implementing stack operations for each application is wasting time and effort!!! Data Structure
3. C Language Implementation • C 배열에 의한 스택 - 두 가지 Top Index 설정법 • Push와 Pop의 인덱스 계산이 달라짐 • 교재 90~94 페이지의 코드는 읽지 않아도 무방함 stack[top++] = item; stack[--top]; stack[++top] = item; stack[top--]; Data Structure
4. Stack ADT • Better strategy - implement a Stack ADT and put it in a library • We can use it whenever we need it. stack.h / stack.c main.c An implementation of Stack ADT Data Structure
4. Stack ADT • Stack ADT Structural Concepts • 교재 96페이지의 Figure3-12 • Stack Structure • P3-06.h • In main() function typedef struct node { void* dataPtr; struct node* link; } STACK_NODE; typedef struct { int count; STACK_NODE* top; } STACK; // Head int* dataPtr STACK* stack; stack = createStack(); dataPtr = (int*) malloc(sizeof(int)); *dataPtr=10; pushStack(stack, dataPtr); … Data Structure
4. Stack ADT • 헤더화일 (교재 97~102 기준) • stacksADT.h #include <stdlib.h> #include "stdbool.h" // instead of <stdbool.h> #include "P3-06.h" /* Stack ADT Definitions */ STACK* createStack (void); bool pushStack (STACK* stack, void* dataInPtr); void* popStack (STACK* stack); void* stackTop (STACK* stack); bool emptyStack (STACK* stack); bool fullStack (STACK* stack); int stackCount (STACK* stack); STACK* destroyStack (STACK* stack); #include "P3-07.h" /* Create Stack */ #include "P3-08.h" /* Push Stack */ #include "P3-09.h" /* Pop Stack */ #include "P3-10.h" /* Retrieve Stack Top */ #include "P3-11.h" /* Empty Stack */ #include "P3-12.h" /* Full Stack */ #include "P3-13.h" /* Stack Count */ #include "P3-14.h" /* DestroyStack */ Data Structure
4. Stack ADT • 헤더화일 (교재 97~102 기준) • stdbool.h #ifndef _STDBOOL_H #define _STDBOOL_H typedef int _Bool; #define bool _Bool #define true 1 #define false 0 #define __bool_true_false_are_defined 1 #endif Data Structure
4. Stack ADT • createStack • P3-07.h STACK* createStack (void) { STACK* stack; stack = (STACK*) malloc( sizeof (STACK)); if (stack) { stack->count = 0; stack->top = NULL; } return stack; } Data Structure
4. Stack ADT • pushStack • P3-08.h bool pushStack (STACK* stack, void* dataInPtr) { STACK_NODE* newPtr; newPtr = (STACK_NODE* ) malloc(sizeof(STACK_NODE)); //1 if (!newPtr) return false; newPtr->dataPtr = dataInPtr; newPtr->link = stack->top; //2 stack->top = newPtr; //3 (stack->count)++; return true; } top newPtr Data Structure
4. Stack ADT • popStack • P3-09.h void* popStack (STACK* stack) { void* dataOutPtr; STACK_NODE* temp; if (stack->count == 0) dataOutPtr = NULL; else { temp = stack->top; //1 dataOutPtr = stack->top->dataPtr; //2 stack->top = stack->top->link; //3 free (temp); (stack->count)--; } return dataOutPtr; } 3 top 1 2 temp dataOutPtr Data Structure
4. Stack ADT • stackTop • P3-10.h • emptyStack • P3-11.h void* stackTop (STACK* stack) { if (stack->count == 0) return NULL; else return stack->top->dataPtr; } bool emptyStack (STACK* stack) { return (stack->count == 0); } Data Structure
4. Stack ADT • fullStack • P3-12.h • stackCount • P3-13.h sizeof(STACK_NODE) 로대신할 수 있음 bool fullStack (STACK* stack) { STACK_NODE* temp; if ((temp = (STACK_NODE*)malloc(sizeof(*(stack->top))))) { free (temp); return false; } return true; } int stackCount (STACK* stack) { return stack->count; } Data Structure
4. Stack ADT • destroyStack • P3-14.h STACK* destroyStack (STACK* stack) { STACK_NODE* temp; if (stack) { while (stack->top != NULL) { free (stack->top->dataPtr); temp = stack->top; stack->top = stack->top->link; free (temp); } free (stack); } return NULL; } STACK* destroyStack (STACK* stack) { STACK_NODE* temp; void* dataPtr; if (stack) { while (stack->top != NULL) { dataPtr = popStack(stack); free(dataPtr); } free (stack); } return NULL; } Data Structure
5. Stack Application • Reversing Data • Reorder a given set of data such that the first and the last elements are exchanged • Expected Execution Enter a number: <EOF> to stop: 3 Enter a number: <EOF> to stop: 5 Enter a number: <EOF> to stop: 7 Enter a number: <EOF> to stop: 16 Enter a number: <EOF> to stop: 91 Enter a number: <EOF> to stop: <CTRL-Z> The list of numbers reversed: 91 16 7 5 3 Data Structure
5. Stack Application #include <stdio.h> #include "stdbool.h" #include "stacksADT.h“ int main (void) { int done = false; int* dataPtr ; STACK* stack ; stack = createStack (); while (!done) { dataPtr = (int*) malloc (sizeof(int)); printf ("Enter a number: <EOF> to stop: "); if ((scanf ("%d" , dataPtr)) == EOF || fullStack (stack)) done = true; else pushStack (stack, dataPtr); } printf ("\n\nThe list of numbers reversed:\n"); while (!emptyStack (stack)) { dataPtr = (int*)popStack (stack); printf ("%3d\n", *dataPtr); free (dataPtr); } destroyStack (stack); return 0; } • Reversing Data • Program Data Structure
5. Stack Application • Reversing Data • Step-by-step Execution Data Structure
5. Stack Application • Convert Decimal to Binary • Expected Execution Enter an integer: 45 // input The binary number is : 101101 // output • Studyyourself (pp.106~107) Data Structure
5. Stack Application • Backtracking (교재 pp.122~ 를 먼저 학습) • Goal seeking • How to find a path from start node to the goal node? • 소모적 탐색(消耗, Exhaustive Search) 방법의 Goal Seeking • 갈 수 있는 길을 무작정 모두 가 보기 • 모든 길을 다 따라 가본 이후에도 목적지에 도달 못하면 가는 길 없는 것으로 결론 • 깊이우선 탐색(DFS, Depth First Search) • 소모적 탐색 방법의 하나 • 깊이를 우선적으로 추구 • 갈 수만 있다면 끝까지 깊숙이 가 본다. • 만약 갈 길이 없다면 이전으로 되돌아 온다. Data Structure
5. Stack Application • 경로를 쫓아가면서 발생하는 경우들 • Goal seeking • Start: A Destination: F • 목적지까지 제대로 간다. • A-B-E-F • Problem 1) 어떤 도시로 갔는데 거기서 더 나갈 곳이 없는 막다른 곳이 된다. • A-G-H • Problem 2) 어떤 길을 따라서 계속 원을 그리며 돈다. • A-B-C-D-B-C-D Data Structure
5. Stack Application • 각 Problem들에 대한 해결책 • “어떤 도시로 갔는데 거기서 더 나갈 곳이 없는 막다른 곳이 된다.” • 규칙: “막힌 도시(Dead End)라면 다시 바로 그 이전 도시로 되돌아온다.” • 되돌아오는 행위를 백 트래킹(Backtracking)이라 함 • 되돌아 간 곳에서 막힌 도시 아닌 다른 곳을 시도 • 방문한 도시를 계속적으로 스택에 Push하면… • 스택의 내용은 A로부터 출발해서 지금까지 방문한 일련의 도시 • 백 트래킹은 스택의 Pop에 해당 • 직전에 거쳐온 도시로 되돌아가는 행위 Data Structure
5. Stack Application • 경로를 쫓아가면서 발생하는 경우들에 대한 해결책 • “어떤 길을 따라서 계속 원을 그리며 돈다.” • 규칙: “한번 방문한 도시는 다시 방문하지 않는다.” (Revisit Avoidance) Data Structure
5. Stack Application • Backtracking • A-G-H에서 백트래킹 • 다시 B를 시도 Data Structure
5. Stack Application • Revisit Avoidance • 스택 내용이 ABCDBE 일 필요가 없음 • 중간의 BCD를 생략하고 ABE로 갈 수 있음 • ABCD에서 B로 가는 것을 미리 막아버림 • 재방문 노드를 발견하면 스택에서 이전에 방문했던 그 노드를 찾을 때까지 Pop을계속함 Data Structure
5. Stack Application • AF 까지의 깊이우선탐색을 위한 스택 변화 알파벳 순서로 노드 선택시 Data Structure
5. Stack Application • A에서 K로 가는 길이 있는가? • 최종적으로 백트랙에 의해 스택이 비어버림. • 그런 경로가 없음을 의미함. Data Structure
5. Stack Application • 교재에서의 방법 Data Structure
5. Stack Application • Parsing - unmatched parentheses • 교과서 페이지 107 Data Structure
5. Stack Application • Parsing - unmatched parentheses • Program 1/2 #include <stdio.h> #include "stacksADT.h“ const char closMiss[ ] = "Close paren missing at line"; const char openMiss[ ] = "Open paren missing at line"; int main (void) { STACK* stack; char token; char* dataPtr; char fileID[25]; FILE* fpIn; int lineCount = 1; stack = createStack (); printf ("Enter file ID for file to be parsed: "); scanf ("%s", fileID); fpIn = fopen (fileID, "r"); if (!fpIn) printf("Error opening %s\n", fileID), exit(100); Data Structure
5. Stack Application • Parsing - unmatched parentheses • Program2/2 while ((token = fgetc (fpIn)) != EOF ) { if (token == '\n') lineCount++; if (token == '(' ) { dataPtr = (char*) malloc (sizeof (char)); pushStack (stack, dataPtr); } else{ if (token == ')'){ if (emptyStack (stack)) { printf ("%s %d\n", openMiss, lineCount); return 1; } else popStack (stack); } } } if (!emptyStack (stack)) { printf ("%s %d\n", closMiss, lineCount); return 1; } destroyStack (stack); printf ("Parsing is OK: %d Lines parsed.\n", lineCount); return 0; } Data Structure