티스토리 뷰

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;

        }

    }

}

'Study > Java' 카테고리의 다른 글

[스터디 5주차] 클래스  (0) 2022.01.09
[스터디 4주차] Queue  (0) 2022.01.02
[스터디 4주차] Stack  (0) 2022.01.02
[스터디 4주차] LinkedList  (0) 2022.01.02
[스터디 4주차] JUnit5  (0) 2022.01.02
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/12   »
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30 31
글 보관함