-
03/30 고정배열로 Stack 구현하기자료구조/수업내용 2021. 3. 30. 14:14
Stack에 필요한 Push, Pop, Peek메서드를 구현
Program.cs
using System; namespace Study09 { class Program { static void Main(string[] args) { Console.WriteLine("Main"); new App(); } } }
StackArray.csusing System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Study09 { public class StackArray { private int top; private string[] arr; public bool IsEmpty { get { return top == -1; } } public int Capacity { get { return arr.Length; } } public StackArray(int capacity) { top = -1; arr = new string[capacity]; } public void Push(string data) { if(top == arr.Length) { ResizeArray(); } arr[++top] = data; } public string Pop() { if(this.IsEmpty) { throw new ApplicationException("Stack is empty."); } return arr[top--]; } public string Peek() { if (this.IsEmpty) { throw new ApplicationException("Stack is empty."); } return arr[top]; } private void ResizeArray() { string[] tmpArr = new string[arr.Length * 2]; Array.Copy(arr, tmpArr, arr.Length); arr = tmpArr; } } }
App.cs
using System; namespace Study09 { public class App { //생성자 public App() { Console.WriteLine("App"); StackArray stackArray = new StackArray(16); stackArray.Push("장검"); stackArray.Push("단검"); stackArray.Push("활"); stackArray.Push("총"); Console.WriteLine("--------------- Pop -------------------"); string data = stackArray.Pop(); Console.WriteLine("Pop : {0} ", data); data = stackArray.Pop(); Console.WriteLine("Pop : {0} ", data); Console.WriteLine(); Console.WriteLine("--------------- Peek -------------------"); data = stackArray.Peek(); Console.WriteLine("Peek : {0} ", data); data = stackArray.Peek(); Console.WriteLine("Peek : {0} ", data); } } }
'자료구조 > 수업내용' 카테고리의 다른 글
03/30 수업내용 메모 (0) 2021.03.30 03/30 단일 연결 리스트로 Stack 구현 (0) 2021.03.30 03/30 단일연결리스트 복습 Add, Count, Print (0) 2021.03.30 03/29 수업내용 메모 (0) 2021.03.29 03/29 동적 배열 구현 연습 (0) 2021.03.29