연결리스트로 스택 구현하기

Algorithm 2019. 8. 28. 17:10
반응형

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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
using System;
 
namespace Application
{
    class MainClass
    {
        public static void Main(string[] args)
        {
            //링크드리스트로 스택 구현 하기
            var stack = new StackUsingLinkedList();
            stack.Push(1);
            stack.Push(2);
            stack.Push(3);
            stack.PrintStack();
            Console.WriteLine("-------------");
            var pop = stack.Pop();
            Console.WriteLine("pop: {0}", pop);
            Console.WriteLine("-------------");
            stack.PrintStack();
            Console.WriteLine("-------------");
            var peek = stack.Peek();
            Console.WriteLine("peek: {0}", peek);
            Console.WriteLine("-------------");
            stack.PrintStack();
 
 
        }
    }
 
    public class StackUsingLinkedList {
 
        private class Node {
            public object Data { get; set; }
            public Node Next { get; set; }
            public Node(object data) {
                this.Data = data;
                this.Next = null;
            }
        }
 
        private Node top = null;
        public bool IsEmpty {
            get { return this.top == null; }
        }
 
        public void Push(object data)
        {
            if (this.top == null)
            {
                this.top = new Node(data);
            }
            else {
                //노드 추가
                var node = new Node(data);
                node.Next = top;
                this.top = node;
            }
        }
 
        public object Pop() {
            if (this.IsEmpty)
            {
                throw new ApplicationException("Empty");
            }
 
            object data = this.top.Data;
            this.top = top.Next;
            return data;
        }
 
        public object Peek()
        {
            if (this.IsEmpty) {
                throw new ApplicationException("Empty");
            }
            return this.top.Data;
        }
 
        public void PrintStack() {
            var temp = this.top;
 
            while (true) {
                Console.WriteLine(temp.Data);
                if (temp.Next == nullbreak;
                temp = temp.Next;
            }
        }
    }
}
 
 
 

 

반응형
: