Week 11-1. (그래픽스 , 자료구조 관련) 스택(stack), 큐 (queue) [Download]

Download Report

Transcript Week 11-1. (그래픽스 , 자료구조 관련) 스택(stack), 큐 (queue) [Download]

응용프로그램
- 그래픽스: 움직이는 도형
- 스택(Stack)
2003. 5. 13.
움직이는 도형
#include<stdio.h>
#include<conio.h>
#include<graphics.h>
#include<dos.h>
void main(void)
{
int i;
int grd=DETECT, grm;
int x=20,y=20;
initgraph(&grd,&grm,"");
* 이동 = 삭제 + 생성
while(!(kbhit()))
{
setcolor(WHITE);
circle(++x,++y,20);
delay(30); /* 잔상 남기기 위해 */
setcolor(BLACK);
circle(x,y,20); /* 이미지 지움 */
if(x>600) { x=20;}
if(y>400) { y=20;}
}
}
2
스택 (Stacks)
Stack이란?

한 쪽 끝에서만 자료의 입력/삭제가 발생하는 연결리스트의 한
형태로서, 가장 나중에 입력한 데이터를 가장 먼저 꺼내게 되는
후입선출(LIFO:last-in first-out)의 특성을 가지는 자료구조
– 삽입(insertion): push
– 삭제(deletion): pop
4
삽입 알고리즘
function ADD(item,stack,n,top)
{
//크기가 n인 스택에 item을 삽입한다//
if top ≥ n then call STACK-FULL
top ←top+1
SATCK(top) ←item
}
5
삭제 알고리즘
function DELETE(item,stack,top)
{
//스택이 공백이 아니면 톱원소를 제거 item에 저장
if top ≤ 0 then call STACK-EMPTY
item ←STACK(top)
top ←top-1
}
6
큐(Queue)란?

한쪽 끝에서 항목(item)이 삭제되고 한쪽 끝에서 항목이
삽입되는 연결리스트의 한 형태
– 스택: top이라 불리는 한쪽 끝에서만 연산이 이루어짐
– 항목들이 삭제되는 끝을 앞(front)이라 하고 삽입되는 끝을
뒤(rear)라 한다.
7
삽입 알고리즘
function ADD(item,Q,n,rear)
{
//Q(1:n)으로 표시된 큐에 item을 삽입한다//
if rear=n then call QUEUE-FULL
rear ←rear+1
Q(rear) ←item
}
8
삭제 알고리즘
function DELETE(item,Q,front,rear)
{
//큐로부터 한 원소를 제거한다.//
if front=rear then call QUEUE-EMPTY
front ←front+1
item ←Q(front)
}
9
Linked Lists
ptr
a1
a2
an
•
typedef struct list_node *list_pointer;
typedef struct list_node {
char data[data];
list_pointer link;
};
list_pointer ptr = NULL;
null list */
/* create a
10
Linked Lists: 새 노드 생성
ptr
ptr = (struct list_node*)malloc(sizeof(struct list_node));
/* 또는 ptr = (list_pointer)malloc(sizeof(struct list_node));
strcpy (ptrdata, “bat”) ;
ptrlink = NULL; /* (ptr  link)  (*ptr).link */
11
Linked Lists: 노드 삽입
q
p
(3)
(1)
(2)
x
(1) p = (list_pointer) malloc ( sizeof (struct
list_node));
pdata = x;
(2) plink = qlink;
(3) qlink = p;
12
Linked Lists: 노드 삭제
q
p
(1)
(3)
(2)
(1) p = q  link;
(2) q  link = (q  link)  link;
(3) free (p);
13
Linked Stacks
top
typedef struct {
int key;
/ * other fields */
} element;
typedef struct stack *stack_pointer ;
typedef struct stack {
element item;
stack_pointer link;
};
stack_pointer top;
14
Linked Stacks: 삽입
void add (stack_pointer *top, element item)
{
(1)
stack_pointer temp = (stack_pointer) malloc (sizeof (stack));
if (IS_FULL (temp))
{
}
temp  item = item;
(2)
temp  link = top;
(3)
top = temp;
top
(3)
(1)
(2)
temp
}
15
Linked Stacks: 삭제
element delete (stack_pointer *top)
{
(1) stack_pointer temp = top;
*top
(2)
element item;
if(IS_EMPTY(temp)){
}
item = temp 
(3)
item ;
(1)
(2)
top = temp  link ;
(3)
free(temp) ;
temp
return item;
}
16
연습문제

스택을 이용 palindrome 검사하기
– 주어진 문자열의 “절반”을 push한 후,
나머지 절반의 문자열의 stack에 들어있는
것과 같은지를 검사
– 예) “reviver”, “Able I was I ere I saw Elba”
17
큐 (Queues)
Linked Queue: 삽입
19
Linked Queue: 삭제
20