ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • 03/30 단일 연결 리스트로 Stack 구현
    자료구조/수업내용 2021. 3. 30. 15:23

     

     

    Program.cs

    using System;
    
    namespace Study09
    {
        class Program
        {
            static void Main(string[] args)
            {
                Console.WriteLine("Main");
                new App();
            }
        }
    }
    

     

    App.cs

    using System;
    
    namespace Study09
    {
    
        public class App
        {
    
            //생성자 
            public App()
            {
                Console.WriteLine("App");
    
                StackLinkedList stack = new StackLinkedList();
                Console.WriteLine("----------- Push ----------------");
                stack.Push("장검");            
                stack.Push("단검");            
                stack.Push("활");
                stack.Push("지팡이");
                stack.Push("둔기");
    
                Console.WriteLine("----------- Pop ----------------");
                Console.WriteLine("Pop : {0}", stack.Pop());
                Console.WriteLine("Pop : {0}", stack.Pop());
                Console.WriteLine();
    
                Console.WriteLine("----------- Peek ---------------");
                Console.WriteLine("Peek :{0}", stack.Peek());
                Console.WriteLine("Peek :{0}", stack.Peek());
            }
    
        }
    }
    

     

     

    StackLinkedList.cs

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    
    namespace Study09
    {
        public class Node
        {
            public string data;
            public Node next;
            public Node(string data)
            {
                this.data = data;
            }
        }
        public class StackLinkedList
        {
            private Node top;
            public StackLinkedList()
            {
    
            }
            public void Push(string data)
            {
                if(top == null)
                {
                    top = new Node(data);
                }
                else
                {
                    Node tmp = new Node(data);
                    tmp.next = top;
                    top = tmp;
                }
                Console.WriteLine("Push :{0}", data);
            }
            public string Pop()
            {
                if(top == null)
                {
                    throw new ApplicationException("Stack is empty");
                }
                string data = top.data;
                top = top.next;
                return data;
            }
            public string Peek()
            {
                if (top == null)
                {
                    throw new ApplicationException("Stack is empty");
                }
                return top.data;
            }
        }
    }
    
Designed by Tistory.