강의자료8

27
1 스스스 ( 스스스스스 스스 스스 )

Upload: young-wook-kim

Post on 11-May-2015

446 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: 강의자료8

1

스택과 큐 ( 연결구조에 의한 구

현 )

Page 2: 강의자료8

2

Definition of Stack

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.

A stack is a LIFO “last in, first out” structure.

Page 3: 강의자료8

Stack ADT Operations

IsEmpty -- Determines whether the stack is currently empty.

IsFull -- Determines whether the stack is currently full.

Push (ItemType newItem) -- Adds newItem to the top of the stack.

Pop (ItemType &item) -- Removes the item at the top of the stack.

3

Page 4: 강의자료8

4

Another Stack Implementation( 스택의 다른 구현방법 )

One advantage of an ADT is that the kind of implementation used can be changed.

The dynamic array implementation of the stack has a weakness -- the maximum size of the stack is passed to the constructor as parameter. ( 스택의 동적 배열의 단점 : 스택의 최대 크기가 생성자에게 전달되어야 됨 )

Instead we can dynamically allocate the space for each stack element as it is pushed onto the stack. ( 스택에 원소가 삽입될 때 이 원소에 대한 메모리 공간을 할당 )

Page 5: 강의자료8

Using operator new

If memory is available in an area called the free store (or heap), operator new allocates the requested object, and returns a pointer to the memory allocated.

( 연산자 new 는 힙 영역의 메모리에 여유공간이 있으면 요청된 객체에 대한 메모리를 할당하고 이의 주소를 반환한다 .)

The dynamically allocated object exists until the delete operator destroys it.

Page 6: 강의자료8

6

ItemType is char

class StackType

StackType

Top

Pop

Push

IsFull

IsEmpty Private data:

topPtr

~StackType

‘C’ ‘V’

노드 (node)

info next

Page 7: 강의자료8

7

class StackType

StackType

Top

Pop

Push

IsFull

IsEmpty Private data:

topPtr

~StackType

23.4 -7.9

ItemType is float

Page 8: 강의자료8

8

// DYNAMICALLY LINKED IMPLEMENTATION OF STACK typedef char ItemType;struct NodeType; //Forward declaration

class StackType{public: //Identical to previous implementationprivate: NodeType* topPtr;};...struct NodeType {

ItemType info;NodeType* next;

};

Page 9: 강의자료8

9

Tracing Client Code

letter ‘V’

char letter = ‘V’;

StackType myStack;

myStack.Push(letter);

myStack.Push(‘C’);

myStack.Push(‘S’);

If (!myStack.IsEmpty() ){ letter = myStack.Top( ); myStack.Pop();}

myStack.Push(‘K’);

Page 10: 강의자료8

10

Adding newItem to the stack

NodeType* location;location = new NodeType<ItemType>;location->info = newItem;location->next = topPtr;topPtr = location;

topPtr ‘X’ ‘C’ ‘L’

‘B’

newItem

Page 11: 강의자료8

11

// DYNAMICALLY LINKED IMPLEMENTATION OF STACK template<class ItemType>struct NodeType {

ItemType info;NodeType* next;

};

template<class ItemType>class StackType{public: //Identical to previous implementation … void Push ( ItemType newItem ); void Pop ( ItemType &item );private: NodeType <ItemType>* topPtr;};

Page 12: 강의자료8

12

template<class ItemType>void StackType <ItemType>::Push ( ItemType newItem )

// Adds newItem to the top of the stack.{

if (IsFull()) { cout << “Stack is full \n”; // throw FullStack(); return; } NodeType* location; location = new NodeType <ItemType> location->info = newItem; location->next = topPtr; topPtr = location;}

Implementing Push

Page 13: 강의자료8

The object currently pointed to by the pointer is deallocated, and the pointer is considered unassigned. The memory is returned to the free store.

Using operator delete

Page 14: 강의자료8

14

Deleting item from the stack

NodeType* tempPtr;

item = topPtr->info;tempPtr = topPtr;topPtr = topPtr->next;delete tempPtr;

topPtr ‘B’ ‘X’ ‘C’ ‘L’

tempPtr

item

Page 15: 강의자료8

15

Deleting item from the stack

NodeType<ItemType>* tempPtr;

item = topPtr->info;tempPtr = topPtr;topPtr = topPtr->next;delete tempPtr;

topPtr

item

‘X’ ‘C’ ‘L’

tempPtr

‘B’

Page 16: 강의자료8

16

template<class ItemType>void StackType <ItemType>::Pop ( ItemType &item )

// Adds newItem to the top of the stack.{ if (IsEmpty()) { cout << “Stack is empty \n”; // throw EmptyStack(); return; }

NodeType <ItemType>* tempPtr;

item = topPtr->info;

tempPtr = topPtr;

topPtr = topPtr->next;

delete tempPtr;}

Implementing Pop

Page 17: 강의자료8

17

Implementing IsFulltemplate<class ItemType>bool StackType <ItemType>::IsFull() const// Returns true if there is no room for another// ItemType on the free store; false otherwise{

NodeType <ItemType>* location;try{ location = new NodeType<ItemType>; delete location; return false;

} catch(std::bad_alloc exception) {

return true; }}

Page 18: 강의자료8

18

Why is a destructor needed?

When a local stack variable goes out of scope, the memory space for data member topPtr is deallocated. But the nodes that topPtr points to are not automatically deallocated. ( 지역 스택 변수가 범위를 벗어나면 topPtr 에 대한 메모리 공간이 해제되지만 topPtr 이 가리키는 노드에 대한 메모리 공간은 해제되지 않는다 .)

A class destructor is used to deallocate the dynamic memory pointed to by the data member. ( 소멸자에서 데이터 멤버가 가리키는 동적 메모리를 해제하여야 한다 .)

Page 19: 강의자료8

19

Implementing the Destructor ( 소멸자 구현 )

template<class ItemType>

StackType <class ItemType> ::~StackType()

// Post: stack is empty;

// All items have been deallocated.

{

NodeType* tempPtr;

while (topPtr != NULL)

{

tempPtr = topPtr;

topPtr = topPtr-> next;

delete tempPtr;

}

}

Page 20: 강의자료8

20

What is a Queue?

Logical (or ADT) level: A queue is an ordered group of homogeneous items (elements), in which new elements are added at one end (the rear), and elements are removed from the other end (the front).

A queue is a FIFO “first in, first out” structure.

Page 21: 강의자료8

Queue ADT Operations

MakeEmpty -- Sets queue to an empty state.

IsEmpty -- Determines whether the queue is currently empty.

IsFull -- Determines whether the queue is currently full.

Enqueue (ItemType newItem) -- Adds newItem to the rear of the queue.

Dequeue (ItemType& item) -- Removes the item at the front of the queue and returns it in item.

21

Page 22: 강의자료8

22

class QueType<char>

QueType

~QueType

Enqueue

Dequeue . . .

Private Data:

qFront

qRear

‘C’ ‘Z’ ‘T’

Page 23: 강의자료8

// DYNAMICALLY LINKED IMPLEMENTATION OF QUEUE template<class ItemType>struct NodeType {

ItemType info;NodeType* next;

};

template<class ItemType>class QueType {public:

QueType( ); // CONSTRUCTOR~QueType( ) ; // DESTRUCTORbool IsEmpty( ) const;bool IsFull( ) const;void Enqueue( ItemType item );void Dequeue( ItemType& item );void MakeEmpty( );

private:NodeType<ItemType>* qFront;NodeType<ItemType>* qRear;

};23

Page 24: 강의자료8

// DYNAMICALLY LINKED IMPLEMENTATION OF QUEUE continued// member function definitions for class QueType

template<class ItemType>QueType<ItemType>::QueType( ) // CONSTRUCTOR{

qFront = NULL;qRear = NULL;

}

template<class ItemType>bool QueType<ItemType>::IsEmpty( ) const{

return ( qFront == NULL )}

24

Page 25: 강의자료8

// DYNAMICALLY LINKED IMPLEMENTATION OF QUEUE continued// member function definitions for class QueType

template<class ItemType>QueType<ItemType>::QueType( ) // CONSTRUCTOR{

qFront = NULL;qRear = NULL;

}

template<class ItemType>bool QueType<ItemType>::IsEmpty( ) const{

return ( qFront == NULL )}

25

Page 26: 강의자료8

template<class ItemType>void QueType<ItemType>::Enqueue( ItemType newItem )

// Adds newItem to the rear of the queue.// Pre: Queue has been initialized./ Queue is not full.// Post: newItem is at rear of queue.

{NodeType<ItemType>* ptr;

ptr = new NodeType<ItemType>;ptr->info = newItem;ptr->next = NULL;if ( qRear == NULL )

qFront = ptr;else

qRear->next = ptr;qRear = ptr;

}26

Page 27: 강의자료8

template<class ItemType>void QueType<ItemType>::Dequeue( ItemType& item )

// Removes element from from front of queue// and returns it in item.// Pre: Queue has been initialized.// Queue is not empty.// Post: Front element has been removed from queue.// item is a copy of removed element.

{NodeType<ItemType>* tempPtr;

tempPtr = qFront;item = qFront->info;qFront = qFornt->next;if ( qFront == NULL )

qRear = NULL;delete tempPtr;

}27