Docsity
Docsity

Prepare for your exams
Prepare for your exams

Study with the several resources on Docsity


Earn points to download
Earn points to download

Earn points by helping other students or get them with a premium plan


Guidelines and tips
Guidelines and tips

Implementation and Analysis of Stacks and Queues using Arrays and Linked Structures, Lecture notes of Data Structures and Algorithms

An in-depth analysis of the implementation and performance of stacks and queues using arrays and linked structures. It covers arraystack, linkedstack, arrayqueue, and linkedqueue, discussing their advantages, disadvantages, and algorithms such as push, pop, enq, and deq. It also introduces the concept of circular linked queues and iterator classes in linked lists.

Typology: Lecture notes

2017/2018

Uploaded on 10/23/2018

keehwan
keehwan 🇨🇦

20 documents

1 / 19

Toggle sidebar

This page cannot be seen from the preview

Don't miss anything!

bg1
자료구조 실습(INA240) NOTE 06
©copyright 2005
연결구조
한국기술교육대학교
한국기술교육대학교 인터넷미디어공학부
인터넷미디어공학부 김상진
김상진
2
2/37
/37
교육목표
연결구조
연결구조를 이용한 스택의 구현
연결구조를 이용한 큐의 구현
연결구조를 이용한 순환 큐의 구현
연결구조를 이용한 정렬 리스트의 구현
연결구조를 이용한 비정렬 리스트 구현
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13

Partial preview of the text

Download Implementation and Analysis of Stacks and Queues using Arrays and Linked Structures and more Lecture notes Data Structures and Algorithms in PDF only on Docsity!

©copyright 2005 자료구조 및 실습( INA240) NOTE 06

3/37 3 /

연결구조란

ArrayList처럼 부족하면 보다 큰 공간을 확보하여 새 공간에

필요필요하다.^ 이것이 연결구조의 한 가지 단점이다.

info info info info info info info info

배열방식 (^) 연결 구조 방식

연결구조 vs. 배열을 이용한 구현 방식

7/37 7 /

연결구조로 스택의 구현

info link info link

A B

info null

C

private class StackNode{ public Object info; public StackNode link; }

LinkedStack stack = new LinkedStack();

stack top null

stack.push(new Integer(10));

stack top info null

10

stack.push(new Integer(20));

stack top

info null

10

info

20

LinkedStack ADT

StackNode top = null;

스택 top을 유지함

LinkedStack()

boolean isFull();

boolean isEmpty();

조건: top==null

void push(Object item);

StackOverflowException이

void pop();

isEmpty()가 참이면

StackUnderflowException

Object top();

isEmpty()가 참이면

StackUnderflowException

stack top null

9/37 9 /

public class LinkedStack implements Stack{ private class StackNode{ public Object item; public StackNode link; } private StackNode top = null; public StackNode() {} … }

Inner Class

내부 클래스(inner class)라 한다.

private class

class

public class

public class

private 내부 클래스는 그것의 외부 클래스를 제외하고는 접근할 수 없으므로 내부 클래스의 멤버 변수를 public으로 선언하여도 안전하다.

Inner Class

(name control 측면)

private 내부 클래스를 사용하여

top level class

inner class

static inner class인 경우에는 가능하지 않다.

13 13/37/

pop

pop 알고리즘

단계 단계 2. top2. 이 top.link을 가리키도록 함

stack top

info null

10

info

20

garbage

public void pop() throws StackUnderflowException{ if(isEmpty()) throw new StackUnderflowException(“…”); top = top.link; }

top

stack top

info null

10

info

20

public Object top() throws StackUnderflowException{ if(isEmpty()) throw new StackUnderflowException(“…”); return top.info; }

15 15/37/

ArrayStack VS. LinkedStack

Which one is better?

공간 활용 측면에서 LinkedStack이 우수

스택의 크기가 매우 가변적인 경우 LinkedStack이 우수

ArrayStack은 공간 낭비 가능

push가 빈번하게 일어나는 경우: ArrayStack 우수

LinkedStack은 매번 새 공간을 확보해야함

constructor O(N) O(1)

space N+1 참조, 1 색인 2N+1 참조 (no waste)

pop O(1) O(1)

push O(1) O(1)

ArrayStack LinkedStack

배열로 큐의 구현

물리적 뷰 vs. 논리적 뷰

ArrayQueue queue = new ArrayQueue(4);

null null null null

0 element

queue front

queue.enq(new Character(‘A’))

element null null null

queue

A

A

rear -1 size^0

front 0 rear 0 size^1

queue.enq(new Character(‘B’))

element null null

queue

A

front 0 rear 1 size^2

B

B A

rear front

rear front

19 19/37/

enqueue

enqueue 알고리즘

단계 단계 2.2. 이 요소의 info 값에 item 할당

단계 단계 3.3. 이 요소를 rear에 추가

단계 4. rear가 이 요소를 가리키도록 변경함

info

10

queue

front rear

info null

20

  1. 생성

public void enq(Object item) { QueueNode newNode = new QueueNode(); newNode.info = item; newNode.link = null; // 큐가 비어 있는 경우 if(rear == null) front = newNode; // 큐에 요소가 있는 경우 else rear.link = newNode; rear = newNode; size++; }

size 2

public Object deq() throws QueueUnderflowException{ if(isEmpty()) throw new QueueUnderflowException(“…”); Object tmp = front.info; front = front.link; size--; if(isEmpty()) rear = null; return tmp; }

dequeue

dequeue 알고리즘

단계 단계 1. queue1. 가 비어있는지 검토

단계 단계 2. front.item2. 을 임시 보관

단계 단계 3. front3. 가 front.link를 가리키도록 변경함

단계 단계 4.4. 큐에 더 이상 요소가 없으면 rear를 null로 설정함

단계 단계 5.5. 임시 보관한 item을 반환

info

10

queue

info null

20

tmp

front rear size 1

21 21/37/

Circular Linked Queue

front만 유지하면 dequeue는 O(1)이지만 enqueue는 O(n)이 된다.

rear만 유지하면 큐 맨 뒤는 rear로 큐 맨 앞은 rear.link로 바로

info

10

queue rear

info

20

info

30

Circular Linked Queue: enq

public void enq(Object item) { QueueNode newNode = new QueueNode(); newNode.info = item; newNode.link = null;

if(rear == null){ // list 가 empty 인 경우

rear = newNode; rear.link = newNode; } else{ newNode.link = rear.link; rear.link = newNode; rear = newNode; } size++; }

info

10

queue rear

info

20

info

30

25 25/37/

Import java.util.Iterator; public abstract class LinkedList implements List{ protected class ListNode{ public Object info; public ListNode next; } // ListNode protected class ListIterator implements Iterator{ … } // ListIterator protected ListNode list = null; protected int size = 0; public LinkedList(){} public boolean isFull(){ return false; } public boolean isEmpty(){ return (list == null); } void clear(){ … } public int size(){ return size; } public Iterator iterator() { return new ListIterator(list); } public abstract boolean search(Object item); public abstract void insert(Object item); public abstract boolean delete(Object item); public abstract Object retrieve(Object item); } // LinkedList

ListNode와 ListIterator 내부 클래스가 protected인 이유는 자식 클래스인 UnsortedLinkedList와 SortedLinkedList에서 활용하기 위함이다.

반복자 클래스

protected class ListIterator implements Iterator{ public ListNode cursor; public int traverseCount = 0; public ListIterator(ListNode node){ cursor = node; } public Object next(){ Object tmp = cursor.info; cursor = cursor.next; traverseCount++; return tmp; } public boolean hasNext(){ return (traverseCount<size); // return (cursor!=null) } public void remove(){ throw new UnsupportedOperationException(); } } // ListIterator

traverseCount 변수를 사용하지 않고 cursor만을 이용하여 구현할 수도 있다. 하지만 CircularLinkedList까지 고려하여 traverseCount 변수를 활용하고 있다.

27 27/37/

UnsortedLinkedList, SortedLinkedList

public class UnsortedLinkedList extends LinkedList{ public UnsortedLinkedList() { super(); } public boolean search(Object item) throws ListUnderflowException{ … } public void insert(Object item){ … } public boolean delete(Object item) throws ListUnderflowException{ … } public Object retrieve(Object item) throws ListUnderflowException{ … } } // UnsortedLinkedList

public class SortedLinkedList extends LinkedList{ public SortedLinkedList() { super(); } public boolean search(Object item) throws ListUnderflowException{ … } public void insert(Object item){ … } public boolean delete(Object item) throws ListUnderflowException{ … } public Object retrieve(Object item) throws ListUnderflowException{ … } } // UnsortedLinkedList

UnsortedLinkedList: search

info

10

info

50

info

30

info

20

loc

public boolean search(Object item) throws ListUnderflowException{ if(isEmpty()) throw new ListUnderflowException(“…”); if(item==null) throw new NullPointerException(“…”); // if(item==null) return false; ListNode loc = list; boolean moreToSearch = true; do{ if(item.equals(loc.info)) return true; else{ loc = loc.next; moreToSearch = (loc != null); } }while(moreToSearch); return false; } // UnsortedList: search

31 31/37/

SortedLinkedList: search

public boolean search(Object item) throws ListUnderflowException{ if(item==null) throw new NullPointerException(“…”); if(isEmpty()) throw new ListUnderflowException(“…”); Comparable x = (Comparable)item; ListNode loc = list; for(int i=0; i<size; i++){ int compResult = x.compareTo(loc.info); if(compResult==0) return true; else if(compResult<0) return false; else loc = loc.next; } // for return false; } // SortedLinkedList: search ( 중간에 중단 가능 )

info

10

info

50

info

30

info

10

list prevLoc loc

public boolean delete(Object item) throws ListUnderflowException{ if(isEmpty()) throw new ListUnderflowException(“…”); if(item==null) throw new NullPointerException(“…”); ListNode loc = list; ListNode prevLoc = null; for(int i=0; i<size; i++){ if(x.equals(loc.info)){ // 삭제할 요소가 있는 경우 if(prevLoc==null) list = list.next; // 리스트의 처음 else prevLoc.next = loc.next; size--; return true; } else{ // 검색을 계속해야 하는 경우 prevLoc = loc; loc = loc.next; } } // for return false; } // UnsortedLinkedList: delete

33 33/37/

SortedLinkedList: delete

public boolean delete(Object item) throws ListUnderflowException{ if(item==null) throw new NullPointerException(“…”); if(isEmpty()) throw new ListUnderflowException(“…”); Comparable x = (Comparable)item; ListNode loc = list; ListNode prevLoc = null; for(int i=0; i<size; i++){ int compResult = x.compareTo(loc.info); if(compResult==0){ // 삭제할 요소가 있는 경우 if(prevLoc==null) list = list.next; // 리스트의 처음 else prevLoc.next = loc.next; size--; return true; } // 삭제할 요소가 없는 경우 else if(compResult<0) return false; else{ // 검색을 계속해야 하는 경우 prevLoc = loc; loc = loc.next; } } // for return false; } // SortedLinkedList: delete

UnsortedLinkedList: insert

info

10

info

50

info

30

info

10

list

info

25

public void insert(Object item){ ListNode newNode = new ListNode(); newNode.info = item; newNode.next = list; list = newNode; size++; } // UnsortedLinkedList: insert

List의 비교

O(N), O(1)

전체: O(N)

O(logN), O(N) 전체: O(N)

O(N), O(1)

전체: O(N)

O(N), O(1)

전체: O(N)

delete

space N+1^ 참조, 2^ 정수 2N+2^ 참조, 1^ 정수 N+1^ 참조, 2^ 정수 2N+2^ 참조, 1^ 정수

O(N), O(1)

전체: O(N)

O(logN), O(N) insert O(1) O(1) 전체: O(N)

retrieve O(N) O(N) O(logN) O(N)

search O(N) O(N) O(logN) O(N)

Unsorted, Array Unsorted, Linked Sorted, Array Sorted, Linked