-
Stack, Queue(1/25)DataStructure & Algorithm 2022. 1. 30. 11:38
1/ Stack
// 스택에 x를 푸시 public int push(int x) throws OverflowIntStackException { if (ptr >= max) // 스택이 가득 참 throw new OverflowIntStackException(); return stk[ptr++] = x; } // 스택에서 데이터를 팝(정상에 있는 데이터를 꺼냄) public int pop() throws EmptyIntStackException { if (ptr <= 0) // 스택이 비어 있음 throw new EmptyIntStackException(); return stk[--ptr]; } // 스택에서 데이터를 피크(정상에 있는 데이터를 들여다봄) public int peek() throws EmptyIntStackException { if (ptr <= 0) // 스택이 비어 있음 throw new EmptyIntStackException(); return stk[ptr - 1]; } // 스택에서 x를 찾아 인덱스(없으면 –1)를 반환 public int indexOf(int x) { for (int i = ptr - 1; i >= 0; i--) // 정상 쪽에서 선형 검색 if (stk[i] == x) return i; // 검색 성공 return -1; // 검색 실패 } // 스택을 비움 public void clear() { ptr = 0; } // 스택의 용량을 반환 public int capacity() { return max; } // 스택에 쌓여 있는 데이터 수를 반환 public int size() { return ptr; } // 스택이 비어 있는가? public boolean isEmpty() { return ptr <= 0; } // 스택이 가득 찼는가? public boolean isFull() { return ptr >= max; } // 스택 안의 모든 데이터를 바닥 → 꼭대기 순서로 출력 public void dump() { if (ptr <= 0) System.out.println("스택이 비어 있습니다."); else { for (int i = 0; i < ptr; i++) System.out.print(stk[i] + " "); System.out.println(); } }
2/ Queue
// 생성자 public IntQueue(int capacity) { num = front = rear = 0; max = capacity; try { que = new int[max]; // 큐 본체용 배열을 생성 } catch (OutOfMemoryError e) { // 생성할 수 없음 max = 0; } } // 큐에 데이터를 인큐 public int enque(int x) throws OverflowIntQueueException { if (num >= max) throw new OverflowIntQueueException(); // 큐가 가득 참 que[rear++] = x; num++; if (rear == max) rear = 0; return x; } // 큐에서 데이터를 디큐 public int deque() throws EmptyIntQueueException { if (num <= 0) throw new EmptyIntQueueException(); // 큐가 비어 있음 int x = que[front++]; num--; if (front == max) front = 0; return x; } // 큐에서 데이터를 피크 (프런트 데이터를 들여다봄) public int peek() throws EmptyIntQueueException { if (num <= 0) throw new EmptyIntQueueException(); // 큐가 비어 있음 return que[front]; } // 큐에서 x를1 검색하여 인덱스(찾지 못하면 –1)를 반환 public int indexOf(int x) { for (int i = 0; i < num; i++) { int idx = (i + front) % max; if (que[idx] == x) // 검색 성공 return idx; } return -1; // 검색 실패 } // 큐를 비움 public void clear() { num = front = rear = 0; } // 큐의 용량을 반환 public int capacity() { return max; } // 큐에 쌓여 있는 데이터 수를 반환 public int size() { return num; } // 큐가 비어 있나요? public boolean isEmpty() { return num <= 0; } // 큐가 가득 찼나요? public boolean isFull() { return num >= max; } // 큐 안의 모든 데이터를 프런트 → 리어 순으로 출력 public void dump() { if (num <= 0) System.out.println("큐가 비어 있습니다."); else { for (int i = 0; i < num; i++) System.out.print(que[(i + front) % max] + " "); System.out.println(); } }
'DataStructure & Algorithm' 카테고리의 다른 글
이진트리 (1/27) (0) 2022.02.05 LinkedList, 재귀알고리즘, 퀵정렬(1/26) (0) 2022.01.30 선택정렬, 삽입정렬, 버블정렬 (1/21) (0) 2022.01.29