What is aStack? Logical (or ADT) level: A stack is an ordered group of homogeneous items (elements), in which the removal and addition of stack items can take place only at the top of the stack. ( 순서가 있는 동형의 원소들의 모임 ; 원소의 삽입과 삭제가 스택의 top 에서만 일어남 ) A stack is a LIFO “last in, first out” structure. ( LIFO 구조 )
3.
스택 추상 데이타타입 순서 리스트의 특별한 경우 순서 리스트 : A=a 0 , a 1 , …, a n-1 , n 0 스택 (stack) 톱 (top) 이라고 하는 한쪽 끝에서 모든 삽입 (push) 과 삭제 (pop) 가 일어나는 순서 리스트 스택 S=(a 0 ,....,a n-1 ): a 0 는 bottom, a n-1 은 top 의 원소 a i 는 원소 a i-1 (0<i<n) 의 위에 있음 후입선출 (LIFO, Last-In-First-Out) 리스트
Stack ADT Operations(ADT 연산 ) MakeEmpty -- Sets stack to an empty state. ( 스택을 빈 상태로 설정 ) IsEmpty -- Determines whether the stack is currently empty. ( 스택에 비어있는지를 판별 ) IsFull -- Determines whether the stack is currently full. ( 스택에 꽉 차 있는지를 판별 ) Push (ItemType newItem) -- error occurs if stack is full; otherwise adds newItem to the top of the stack. 원소의 삽입 ( 스택이 full 이면 오류 발생 ) Pop (ItemType &item) – error occurs if stack is empty; otherwise removes the item at the top of the stack. 원소의 삭제 ( 스택이 empty 이면 오류 발생 )
Typedef int ItemType;Const maxStack = 100; class StackType { public: StackType( ); // Class constructor. void MakeEmpty(); // Function: Make the stack empty. // Pre: None. // Post: Stack becomes empty. bool IsFull () const; // Function: Determines whether the stack is full. // Pre: Stack has been initialized // Post: Function value = (stack is full)
8.
bool IsEmpty() const;// Function: Determines whether the stack is empty. // Pre: Stack has been initialized. // Post: Function value = (stack is empty) void Push( ItemType item ); // Function: Adds newItem to the top of the stack. // Pre: Stack has been initialized. // Post: If (stack is full), error occurs ; // otherwise, newItem is at the top of the stack. void Pop(ItemType &item); // Function: Removes top item from the stack. // Pre: Stack has been initialized. // Post: If (stack is empty), error occurs ; // otherwise, top element has been removed from stack. private: int top; ItemType items[maxStack]; };
9.
Class Interface 및 Stack 의 배열 구현 StackType class StackType Pop Push IsFull IsEmpty Private data: top [maxStack] . . . [ 2 ] [ 1 ] items [ 0 ] MakeEmpty
Tracing Client Codechar letter = ‘V’; StackType charStack; charStack.Push(letter); charStack.Push(‘C’); charStack.Push(‘S’); if ( !charStack.IsEmpty( )) charStack.Pop( ); charStack.Push(‘K’); while (!charStack.IsEmpty( )) { letter = charStack.Top(); charStack.Pop(0)} Private data: top [ MAX_ITEMS-1 ] . . . [ 2 ] [ 1 ] items [ 0 ] letter ‘ V’
12.
What is aGeneric Data Type? A generic data type is a type for which the operations are defined but the types of the items being manipulated are not defined. 연산들은 정의되어 있지만 처리하는 원소 ( 항목 ) 들의 자료형은 정의되어 있지 않은 자료형
13.
What is aClass Template? Generic data type 을 정의할 수 있게 해 주는 C++ 구조 A class template allows the compiler to generate multiple versions of a class type by using type parameters. class template: 자료형의 인자를 사용하여 클래스 자료형의 여러 버전을 생성할 수 있도록 해 줌 The formal parameter appears in the class template definition, and the actual parameter appears in the client code. Both are enclosed in pointed brackets, < >. 자료형의 형식인자가 클래스 template 정의에 있어야 하고 실제인자는 client 코드에서 주어짐
Using class templatesThe actual parameter to the template is a data type. Any type can be used, either built-in or user-defined. (template 의 실제인자는 자료형 ) When creating class template Put .h and .cpp in same file or Have .h include .cpp file
20.
What is apointer variable? A pointer variable is a variable whose value is the address of a location in memory. ( 포인터 변수 : 메모리의 주소 값을 가지는 변수 ) To declare a pointer variable, you must specify the type of value that the pointer will point to. For example, 포인터 변수선언시 포인터가 가리키는 값의 자료형을 명시하여야 함 int* ptr; // ptr will hold the address of an int char* q; // q will hold the address of a char
21.
Using a pointervariable int x; x = 12; int* ptr; ptr = &x; NOTE: Because ptr holds the address of x, we say that ptr “points to” x . 2000 12 x 3000 2000 ptr
22.
C++ DataTypes Structured array struct union class Simple Integral Floating char short int long enum float double long double Address pointer reference
23.
The NULLPointer There is a pointer constant 0 called the “null pointer” denoted by NULL in cstddef. But NULL is not memory address 0. NOTE: It is an error to dereference a pointer whose value is NULL. Such an error may cause your program to crash, or behave erratically. It is the programmer’s job to check for this. while (ptr != NULL) { . . . // ok to use *ptr here }
24.
Allocation of memory( 메모리 할당 ) STATIC ALLOCATION ( 정적할당 ) Static allocation is the allocation of memory space at compile time. ( 컴파일시 메모리 공간을 할당 ) DYNAMIC ALLOCATION ( 동적 할당 ) Dynamic allocation is the allocation of memory space at run time by using operator new. ( 실행시 new 연산자를 사용하여 메모리 공간을 할당 )
25.
3 Kinds ofProgram Data STATIC DATA: memory allocation exists throughout execution of program. ( 프로그램이 실행시부터 끝까지 메모리 할당이 유지 ) static long SeedValue; AUTOMATIC DATA: automatically created at function entry, resides in activation frame of the function, and is destroyed when returning from function. ( 함수 진입시 메모리 할당 ; 함수로부터 return 시 메모리 해제 ) DYNAMIC DATA: explicitly allocated and deallocated during program execution by C++ instructions written by programmer using unary operators new and delete . ( 프로그램 수행시 new 에 의하여 메모리 할당 ; delete 에 의하여 메모리 해제 )
26.
Using operator newIf memory is available in an area called the free store (or heap), operator new allocates the requested object or array, and returns a pointer to (address of ) the memory allocated. 힙이라는 메모리공간에 사용가능한 메모리가 남아 있으면 , new 는 요청한 만큼의 메모리를 할당하고 할당한 메모리의 주소를 반환 Otherwise, the null pointer 0 is returned. The dynamically allocated object exists until the delete operator destroys it.
The object orarray currently pointed to by the pointer is deallocated, and the pointer is considered unassigned. The memory is returned to the free store. 포인터가 가리키는 메모리 공간을 해제 ; 힙에 돌려줌 Square brackets are used with delete to deallocate a dynamically allocated array of classes. Using operator delete
29.
Some C++ pointeroperations Precedence Higher -> Select member of class pointed to Unary: ++ -- ! * new delete Increment, Decrement, NOT, Dereference, Allocate, Deallocate * / % + - Add Subtract < <= > >= Relational operators == != Tests for equality, inequality Lower = Assignment
30.
Dynamic Array Allocation char *ptr; // ptr is a pointer variable that // can hold the address of a char ptr = new char[ 5 ]; // dynamically, during run time, allocates // memory for 5 characters and places into // the contents of ptr their beginning address ptr 6000 6000
Dynamic Array Deallocation char *ptr ; ptr = new char[ 5 ]; strcpy( ptr, “Bye” ); ptr[ 1 ] = ‘u’; delete ptr; // deallocates array pointed to by ptr // ptr itself is not deallocated, but // the value of ptr is considered unassigned ptr ?
33.
int* ptr =new int; *ptr = 3; ptr = new int; // changes value of ptr *ptr = 4; What happens here? 3 ptr 3 ptr 4
34.
Memory Leak Amemory leak occurs when dynamic memory (that was created using operator new) has been left without a pointer to it by the programmer, and so is inaccessible. 동적메모리를 가리키는 포인터가 없으면서 할당된 상태로 남아 있음 ; 접근 불가능 int* ptr = new int; *ptr = 8; int* ptr2 = new int; *ptr2 = -5; How else can an object become inaccessible? 8 ptr -5 ptr2
35.
Causing a MemoryLeak int* ptr = new int; *ptr = 8; int* ptr2 = new int; *ptr2 = -5; ptr = ptr2; // here the 8 becomes inaccessible 8 ptr -5 ptr2 8 ptr -5 ptr2
36.
occurs when twopointers point to the same object and delete is applied to one of them. 두개의 포인터가 같은 객체를 가리키고 있는 상태에서 이들 포인터 중 하나에 delete 가 적용됨 int* ptr = new int; *ptr = 8; int* ptr2 = new int; *ptr2 = -5; ptr = ptr2; A Dangling Pointer 8 ptr -5 ptr2 FOR EXAMPLE,
37.
int* ptr =new int; *ptr = 8; int* ptr2 = new int; *ptr2 = -5; ptr = ptr2; delete ptr2; // ptr is left dangling ptr2 = NULL; Leaving a Dangling Pointer 8 ptr NULL ptr2 8 ptr -5 ptr2
// StackType classtemplate template<class ItemType> class StackType { public: StackType(int max ); // max is stack size StackType(); // Default size is 500 // Rest of the prototypes go here. private: int top; int maxStack; // Maximum number of stack items. ItemType* items; // Pointer to dynamically allocated memory };
40.
// Implementation ofmember function templates template<class ItemType> StackType<ItemType>::StackType(int max) // parameterized class constructor { maxStack = max; top = -1; items = new ItemType[maxStack]; } template<class ItemType> StackType<ItemType>::StackType() // default class constructor { maxStack = 500; top = -1; items = new ItemType[max]; }
41.
// Templated StackTypeclass variables declared StackType<int> myStack(100); // Stack of at most 100 integers. StackType<float> yourStack(50); // Stack of at most 50 floating point values. StackType<char> aStack; // Stack of at most 500 characters.
42.
스택의 응용 함수호출과 return 의 구현 1. 함수 호출시 return address 를 스택에 push 2. 함수 수행을 끝내고 return 할 때 돌아갈 주소는 스택에서 pop 식의 표기방법 opr1: 왼쪽 피연산자 opr2: 오른쪽 피연산자 op: 연산자 1. infix notation: opr1 op opr2 2. prefix notation: op opr1 opr2 3. postfix notation: opr1 opr2 op
43.
함수 호출과 return 의 구현 시스템 스택 프로그램 실행시 함수 호출을 처리 함수 호출시 활성 레코드 (activation record) 또는 스택 프레임 (stack frame) 구조 생성하여 시스템 스택의 톱에 둔다 . 이전의 스택 프레임에 대한 포인터 복귀 주소 지역 변수 매개 변수 함수가 자기자신을 호출하는 순환 호출도 마찬가지로 처리 순환 호출시마다 새로운 스택 프레임 생성 최악의 경우 가용 메모리 전부 소모
44.
함수 호출과 return 의 구현 주 함수가 함수 a1 을 호출하는 예 함수 호출 뒤의 시스템 스택
45.
수식의 표현방법 예infix 수식 : a * (b + c ) – d prefix 수식 : - * a + b c d postfix 수식 : a b c + * d - Infix 식 : 결과값을 계산하는데 연산자의 우선순위를 고려해야 하므로 시간에 있어서 비효율적 Prefix 식 , Postfix 식 : 결과값을 계산하는데 간편하다 ( 효율적이다 ).
46.
Postfix 수식의계산 스택을 이용하여 계산 while( 수식에서 입력할 것이 있으면 ) { 수식에서 입력하여 이를 변수 x 에 저장 x 가 operand 이면 스택에 push x 가 operator 이면 opr2 스택에서 pop opr1 스택에서 pop opr1 op opr2 를 계산하여 이를 스택에 push } 수식의 결과값 스택에서 pop
47.
Infix 수식의 Postfix 수식변환 1. Infix 수식을 괄호로 묶는다 . 2. 모든 연산자를 해당하는 ‘ ) ’ 바로 앞으로 보낸다 . 3. 모든 괄호를 제거한다 . infix 수식 : a * (b + c ) – d ((a * (b + c )) – d) ((a (b c +) *) d -) a b c + * d -
48.
Infix 수식의 Postfix 수식변환 스택을 이용하여 변환 수식을 왼쪽에서부터 차례대로 x 에 읽어 들임 if (x 가 피연산이면 ) output x; else if (x 가 ‘ ( ‘ 이면 스택에 push) else if (x 가 ‘ ) ’ 이면 ) 스택에서 ‘ ( ‘ 를 만날 때까지 스택에서 pop 하여 이를 output else 다음을 반복 { 스택에 있는 것보다 우선순위가 높으면 {x 를 push; continue} 그렇지 않으면 스택에서 pop 하여 이를 output }
49.
예 a *(b + c ) – d => output a -- 출력결과 a a * (b + c ) – d => 스택에 * 를 push a * (b + c ) – d => 스택에 ( 를 push a * (b + c ) – d => output b -- 출력결과 a b a * (b + c ) – d => 스택에 + 를 push a * (b + c ) – d => output c -- 출력결과 a b c a * (b + c ) – d => 스택에서 pop -- 출력결과 a b c + * ( * * ( + *
50.
예 a *(b + c ) – d => 스택에서 pop -- 출력결과 a b c + a * (b + c ) – d => 스택에서 pop -- 출력결과 a b c + * 스택에 – 를 push a * (b + c ) – d => output d -- 출력결과 a b c + * d a * (b + c ) – d => 스택에서 pop -- 출력결과 a b c + * d - -