๐ฅ using array
import java.util.NoSuchElementException;
public class StackImpl {
static final int STACK_SIZE = 3;
int size=STACK_SIZE;
// ๋ค์์ ๋ค์ด๊ฐ ๊ฐ์ ๊ฐ๋ฅดํด
int index=0;
int[] arr = new int[STACK_SIZE];
void push(int val){
if(isStackOverSize()){
extendStackSize();
}
arr[index++]=val;
}
int pop(){
if (index==0){
throw new NoSuchElementException();
}
// index๊ฐ ๋ค์์ ๋ค์ด๊ฐ ๊ฐ์ ๊ฐ๋ฅดํค๊ธฐ ๋๋ฌธ์ ๋ฏธ๋ฆฌ ๋นผ์ฃผ์ด์ผ ํ๋ค.
return arr[--index];
}
public String toString(){
StringBuilder sb = new StringBuilder();
sb.append("[");
for(int i=0;i<index;i++){
sb.append(arr[i]);
if(i!=index-1){
sb.append(",");
}
}
sb.append("]");
return sb.toString();
}
boolean isStackOverSize(){
return index >= size;
}
void extendStackSize(){
int[] temp = arr;
size = index*STACK_SIZE;
arr = new int[size];
for(int i=0;i<index;i++){
arr[i] = temp[i];
}
}
}
๐ฅ using node
import java.util.NoSuchElementException;
public class QueueImpl {
class Node{
int val;
Node next;
Node(int val){
this.val=val;
}
}
Node first;
Node last;
void offer(int val){
Node node = new Node(val);
if(last!=null){
last.next=node;
}
last = node;
// ์ฒซ๋ฒ์งธ ๊ฐ์ ๋ฃ์์ ๋ first = null ์ ๊ทธ๋์ first = last ์์ผ์ค์ผ ํ๋ค
if(first==null){
first=last;
}
}
int poll(){
if (first==null){
throw new NoSuchElementException();
}
int returnValue = first.val;
first= first.next;
// last์ ๋ํ ์ค์ ๊ฐ๋ ํด์ฃผ์ด์ผ ํ๋ค.
if(first==null){
last=null;
}
return returnValue;
}
public String toString(){
StringBuilder sb = new StringBuilder();
sb.append("[");
Node node = this.first;
while(node!=null){
sb.append(node.val);
if(node.next!=null){
sb.append(",");
}
node=node.next;
}
sb.append("]");
return sb.toString();
}
}