1 / 29

Data Structures chap5 Stack

Data Structures chap5 Stack. 서국화 kookhwa@kunsan.ac.kr 군산대학교 통계컴퓨터과학과 IST 연구실 2012. 4. 13. 목 차. 스택 추상 데이터 타입 배열로 구현한 스택 연결 리스트로 구현한 스택 괄호 검사 수식의 계산 미로 탐색 문제. 스택 추상 데이터 타입 (1/2). 요소 (element ) : 스택에 저장되는 것. 스택 상단 (top ) : 데이터 입출력이 이루어지는 부분. C. B. 스택 하단 (bottom ). A.

kelton
Télécharger la présentation

Data Structures chap5 Stack

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Data Structureschap5 Stack 서국화 kookhwa@kunsan.ac.kr 군산대학교 통계컴퓨터과학과 IST 연구실 2012. 4. 13

  2. 목 차 스택 추상 데이터 타입 배열로 구현한 스택 연결 리스트로 구현한 스택 괄호 검사 수식의 계산 미로 탐색 문제 IST (Information Sciences & Technology) Laboratory

  3. 스택 추상 데이터 타입(1/2) 요소(element) : 스택에 저장되는 것 스택 상단(top) : 데이터 입출력이 이루어지는 부분 C B 스택 하단(bottom) A • 스택 • 후입 선출 입출력 형태의 자료구조 • 스택의 중간에서는 삭제 불가능 IST (Information Sciences & Technology) Laboratory

  4. 스택 추상 데이터 타입 (2/2) • 스택의 연산 • Push : 삽입연산 • Pop : 삭제연산 • Is_empty : 공백 상태 확인 • Is_full : 포화 상태 확인 • Create : 스택 생성 • Peek : 요소 보기 IST (Information Sciences & Technology) Laboratory

  5. 배열로 구현한 스택(1/6) top 1차원 배열 stack[ ] 4 4 3 3 2 2 1 1 0 0 -1 top -1 포화상태 공백상태 top 변수 : 스택에서 최근에 입력되었던 자료를 가리키는 변수 가장 먼저 들어온 요소는 stack[0]에, 가장 최근에 들어온 요소는 stack[top]에 저장 스택이 공백상태이면 top은 -1 IST (Information Sciences & Technology) Laboratory

  6. 4 4 3 3 2 2 top 1 1 top 0 0 배열로 구현한 스택(2/6) push(S, x) if is_full(S) then error "overflow" elsetop←top+1           stack[top]←x push 연산 IST (Information Sciences & Technology) Laboratory

  7. 4 4 3 3 2 2 top top 1 1 0 0 배열로 구현한 스택(3/6) pop(S, x) if is_empty(S) then error "underflow" elsee ← stack[top] top←top-1 return e pop 연산 IST (Information Sciences & Technology) Laboratory

  8. 배열로 구현한 스택(4/6) is_empty(S) iftop = -1 then return TRUE else return FALSE is_full(S) iftop = (MAX_STACK_SIZE-1) then return TRUE else return FALSE 4 top 4 3 3 2 2 1 1 0 0 -1 top -1 포화상태 공백상태 is_empty, is_full연산의 구현 IST (Information Sciences & Technology) Laboratory

  9. #include <stdio.h> #include <string.h> #define MAX_STACK_SIZE 100 #define MAX_STRING 100 typedefstruct { intstudent_no; char name[MAX_STRING]; char address[MAX_STRING]; } StackObject; StackObject stack[MAX_STACK_SIZE]; int top = -1; void initialize(){ top = -1; } intisEmpty(){ return (top == -1); } intisFull(){ return (top == (MAX_STACK_SIZE-1)); } 배열로 구현한 스택(5/6) 구조체 배열 스택 프로그램 IST (Information Sciences & Technology) Laboratory

  10. 배열로 구현한 스택(6/6) void push(StackObject item){ if( isFull() ) { printf("stack is full\n"); } else stack[++top] = item; } StackObject pop() { if( isEmpty() ) { printf("stack is empty\n"); } else return stack[top--]; } void main(){ StackObjectie; StackObjectoe; strcpy(ie.name, "HongGilDong"); strcpy(ie.address, "Seoul"); ie.student_no = 20053001; push(ie); oe = pop(); printf("name: %s\n", oe.name); printf("address: %s\n", oe.address); printf("student number: %d\n", oe.student_no); } 구조체 배열 스택 프로그램 IST (Information Sciences & Technology) Laboratory

  11. 3 9 7 연결 리스트로 구현한 스택(1/5) 동적으로 할당받은 메모리를 해제 시켜줘야 하기 때문에 4 3 top top 2 9 1 7 3 NULL 0 연결리스트를 이용하여 구현한 스택 장점 : 크기가 제한되지 않음 단점 : 구현이 복잡하고 삽입이나 삭제 시간이 오래 걸림 IST (Information Sciences & Technology) Laboratory

  12. C A B D top NULL (2) (1) temp 연결 리스트로 구현한 스택 (2/5) 연결된 스택에서push 연산 IST (Information Sciences & Technology) Laboratory

  13. top NULL temp C A B 연결 리스트로 구현한 스택 (3/5) 연결된 스택에서pop 연산 IST (Information Sciences & Technology) Laboratory

  14. 연결 리스트로 구현한 스택 (4/5) #include <stdio.h> #include <malloc.h> typedefint element; typedefstructStackNode { element item; structStackNode *link; }StackNode; typedefstruct { StackNode *top; }LinkedStackType; void init(LinkedStackType *s){ s->top = NULL; } intis_empty(LinkedStackType *s){ return (s->top == NULL); } intis_full(LinkedStackType *s){ return 0; //스택의 사이즈 제한이 없으므로 항상 꽉 차 있지 않음. } void push(LinkedStackType *s, element item){ StackNode *temp = (StackNode *)malloc(sizeof(StackNode)); if( temp == NULL ){ fprintf(stderr, "메모리 할당에러\n"); return; } 연결된 스택에서 프로그램 IST (Information Sciences & Technology) Laboratory

  15. else{ temp->item = item; temp->link = s->top; s->top = temp; } } element pop(LinkedStackType *s) { if( is_empty(s) ) { fprintf(stderr, "스택이 비어 있음\n"); exit(1); } else{ StackNode *temp=s->top; element item = temp->item; s->top = s->top->link; free(temp); return item; } } element peek(LinkedStackType *s) { if( is_empty(s) ) { fprintf(stderr, "스택이 비어 있음\n"); exit(1); } else{ return s->top->item; } } void main(){ LinkedStackType *s; push(&s, 1); push(&s, 2); push(&s, 3); printf("%d\n", pop(&s)); printf("%d\n", pop(&s)); printf("%d\n", pop(&s)); printf("%d\n", is_empty(&s)); } 연결 리스트로 구현한 스택 (5/7) 연결된 스택에서 프로그램 IST (Information Sciences & Technology) Laboratory

  16. 괄호 검사 (1/5) { A [ (i+1 ) ]=0; } 비교 비교 비교 성공 [ { ( ( [ [ [ { { { { { • 잘못된 괄호 사용의 예 • {A[(i+1)]=0;} 오류 X • if((i==0) && (j==0) 괄호개수 부족 • A[(i+1])=0; 괄호 matching X IST (Information Sciences & Technology) Laboratory

  17. 괄호 검사 (2/5) if( ( i==0 ) && (j==0 ) ) 비교 비교 오류 ( ( ( ( ( ( ( ( ( ( 괄호 검사 과정 IST (Information Sciences & Technology) Laboratory

  18. 괄호 검사 (3/5) #include <stdio.h> #include <stdlib.h> #include <stdio.h> #define TRUE 1 #define FALSE 0 #define MAX_STACK_SIZE 100 typedef char element; typedefstruct { element stack[MAX_STACK_SIZE]; int top; } StackType; // 스택 초기화 함수 void init(StackType *s){ s->top = -1; } // 공백 상태 검출 함수 intis_empty(StackType *s){ return (s->top == -1); } // 포화 상태 검출 함수 intis_full(StackType *s){ return (s->top == (MAX_STACK_SIZE-1)); } 괄호 검사 프로그램 IST (Information Sciences & Technology) Laboratory

  19. 괄호 검사 (4/5) void push(StackType *s, element item) // 삽입함수 { if( is_full(s) ) { fprintf(stderr,"스택 포화 에러\n"); return; } else s->stack[++(s->top)] = item; } element pop(StackType *s) // 삭제함수 { if( is_empty(s) ) { fprintf(stderr, "스택 공백 에러\n"); exit(1); } else return s->stack[(s->top)--]; } intcheck_matching(char *in) { StackType s; char ch, open_ch; inti, n = strlen(in); init(&s); for (i = 0; i < n; i++) { ch = in[i]; switch(ch){ case '(': case '[': case '{': push(&s, ch); break; case ')': case ']': case '}': if(is_empty(&s)) return FALSE; 괄호 검사 프로그램 IST (Information Sciences & Technology) Laboratory

  20. 괄호 검사 (5/5) else { open_ch = pop(&s); if ((open_ch == '(' && ch != ')') || (open_ch == '[' && ch != ']') || (open_ch == '{' && ch != '}')) { return FALSE; } break; } } } if(!is_empty(&s)) return FALSE; return TRUE; } int main(){ if( check_matching("{ A[(i+1)]=0; }") == TRUE ) printf("괄호검사성공\n"); else printf("괄호검사실패\n"); } 괄호 검사 프로그램 IST (Information Sciences & Technology) Laboratory

  21. 수식의 계산 (1/4) • 수식 표기법 • 전위(prefix) : 연산자가 피연산자 앞에 위치 • 중위(infix) : 연산자가 피연산자 사이에 위치 • 후위(postfix) : 연산자가 피연산자 뒤에 위치 IST (Information Sciences & Technology) Laboratory

  22. 수식의 계산 (2/4) 왜냐하면 후기표기방식을 쓰면괄호를 쓰지 않고도 우선순위가 표현되기 때문에 • 컴퓨터에서의 수식 계산순서 • 중위표기식을후위표기식으로 변환하여 계산 • 2+3*4 -> 234*+ = 14 IST (Information Sciences & Technology) Laboratory

  23. 수식의 계산 (3/4) typedef char element; // 연산자의 우선순위를 반환한다. intprec(char op){ switch(op){ case '(': case ')': return 0; case '+': case '-': return 1; case '*': case '/': return 2; } return -1; } // 중위 표기 수식 -> 후위 표기 수식 void infix_to_postfix(char exp[]){ inti=0; char ch, top_op; intlen=strlen(exp); StackType s; init(&s); // 스택 초기화 for(i=0; i<len; i++){ ch = exp[i]; switch(ch){ case ‘+’ : case ‘-’ : case ‘*’ : case ‘/’ : // 연산자 // 스택에 있는 연산자의 우선순위가 더 크거나 같으면 출력 while(!is_empty(&s) && (prec(ch) <= prec(peek(&s)))) printf("%c", pop(&s)); push(&s, ch); break; 후위 표기 수식으로 변환하는 프로그램 IST (Information Sciences & Technology) Laboratory

  24. 수식의 계산 (4/4) case ‘(’ : // 왼쪽 괄호 push(&s, ch); break; case ‘)’ : // 오른쪽 괄호 top_op = pop(&s); // 왼쪽 괄호를 만날때까지 출력 while( top_op != '(' ){ printf("%c", top_op); top_op = pop(&s); } break; default : // 피연산자 printf("%c", ch); break; } } while( !is_empty(&s) ) // 스택에 저장된 연산자들 출력 printf("%c", pop(&s)); } main(){ infix_to_postfix("(2+3)*4+9"); } 후위 표기 수식으로 변환하는 프로그램 IST (Information Sciences & Technology) Laboratory

  25. 미로 탐색 문제 (1/4) 입구 출구 현재의 위치에서 이동 가능한 모든 경로를 스택에 저장해놓았다가 막다른 길을 만나면 스택에서 다음 탐색 위치를 꺼내는 원리를 이용함 IST (Information Sciences & Technology) Laboratory

  26. 미로 탐색 문제 (2/4) 미로탐색 원리 IST (Information Sciences & Technology) Laboratory

  27. 미로 탐색 문제 (3/4) #include <stdio.h> #include <string.h> #define MAZE_SIZE 6 typedefstruct { short r; short c; } element; element here={1,0}, entry={1,0}; char maze[MAZE_SIZE][MAZE_SIZE] = { {'1', '1', '1', '1', '1', '1'}, {'e', '0', '1', '0', '0', '1'}, {'1', '0', '0', '0', '1', '1'}, {'1', '0', '1', '0', '1', '1'}, {'1', '0', '1', '0', '0', 'x'}, {'1', '1', '1', '1', '1', '1'}, }; void push_loc(StackType *s, int r, int c){ if( r < 0 || c < 0 ) return; if( maze[r][c] != '1' && maze[r][c] != '.' ){ element tmp; tmp.r = r; tmp.c = c; push(s, tmp); } } 미로 탐색 프로그램 IST (Information Sciences & Technology) Laboratory

  28. 미로 탐색 문제 (4/4) void main(){ intr,c; StackType s; init(&s); here=entry; while ( maze[here.r][here.c]!='x' ){ //x는 도착지점 r = here.r; c = here.c; maze[r][c] = '.'; pushLoc(r-1,c); pushLoc(r+1,c); pushLoc(r,c-1); pushLoc(r,c+1); if( is_empty(&s) ){ printf("실패\n"); return; } else here = pop(&s); } //while문 끝 printf("성공\n"); } 미로 탐색 프로그램 IST (Information Sciences & Technology) Laboratory

  29. 감사합니다 서국화 kookhwa@kunsan.ac.kr

More Related