Study/Spring & Java
[스터디 4주차] LinkedList로 Stack 구현
나갱
2022. 1. 2. 23:56
Linked List로 Stack 구현 실습
class ListNode {
int data;
ListNode next;
public ListNode(int data, ListNode next) {
this.data = data;
this.next = next;
}
public ListNode(int data) {
this.data = data;
this.next = null;
}
ListNode add(ListNode head, ListNode nodeToAdd, int position) {
if (head == null) {
head = nodeToAdd;
} else {
ListNode node = head;
for (int i = 0; i < position - 1; i++) {
node = node.next;
}
nodeToAdd.next = node.next;
node.next = nodeToAdd;
}
return head;
}
public ListNode remove(ListNode head, int positionToRemove) {
if (head == null) {
return head;
}
if (positionToRemove == 0) {
head = head.next;
return head;
}
ListNode node = head;
for (int i = 0; i < positionToRemove - 1; i++) {
if (node == null) {
return head;
}
node = node.next;
}
node.next = node.next.next;
return head;
}
boolean contains(ListNode head, ListNode nodeToCheck) {
ListNode node = head;
while (node != null) {
if (node.data == nodeToCheck.data) {
return true;
}
node = node.next;
}
return false;
}
}
public class LinkedListStack {
private ListNode head;
private int top = 0;
public LinkedListStack(){
}
public LinkedListStack(int data){
ListNode push = new ListNode(data);
if(head == null){
head = new ListNode(data);
top++;
}else{
head.add(head, new ListNode(data), top++);
}
System.out.println(head);
}
// 삽입
public void push(int data){
if(head == null){
head = new ListNode(data);
top++;
}else{
head.add(head, new ListNode(data), top++);
}
System.out.println(head);
}
//삭제
public int pop(){
if(top == 0) {
System.out.println("데이터가 존재하지 않습니다.");
return -1;
}else{
ListNode node =head;
for(int i=0; i<top-1; i++){
node = node.next;
}
int data = node.data;
// public ListNode remove(ListNode head, int positionToRemove){
node.remove(head, --top);
return data;
}
}
}