Skip to content

Instantly share code, notes, and snippets.

@Youngchangoon
Last active May 13, 2019 23:06
Show Gist options
  • Save Youngchangoon/aa2688406f2005fb7e94d5f0be9cc7a0 to your computer and use it in GitHub Desktop.
Save Youngchangoon/aa2688406f2005fb7e94d5f0be9cc7a0 to your computer and use it in GitHub Desktop.
Stack ( linked list )
using System;
namespace ConsoleApp1
{
public class Program
{
private static StackSingleList<int> singleLinkedList;
static void Main(string[] args)
{
singleLinkedList = new StackSingleList<int>();
// Push
Console.WriteLine("Push 100"); singleLinkedList.Push(100);
Console.WriteLine("Push 200"); singleLinkedList.Push(200);
Console.WriteLine("Push 300"); singleLinkedList.Push(300);
// Top
Console.WriteLine("TOP is: " + singleLinkedList.Top());
// Pop
Console.WriteLine("Pop Data is: " + singleLinkedList.Pop());
Console.WriteLine("Pop Data is: " + singleLinkedList.Pop());
// IsEmpty
Console.WriteLine("IsEmpty: " + singleLinkedList.IsEmpty());
singleLinkedList.PrintNode();
}
}
public class StackSingleList<T>
{
public class Node<T>
{
public Node() { }
public Node(T newData)
{
data = newData;
}
public T data;
public Node<T> next;
}
private Node<T> head;
private Node<T> tail;
public StackSingleList()
{
// 먼저 머리와 꼬리 노드를 만들어준다. ㅁ(head) -> ㅁ(tail)
head = new Node<T>();
tail = new Node<T>();
// (head) -> tail
head.next = tail;
// (tail) -> NULL
tail.next = null;
}
public void Push(T data)
{
Node<T> newNode = new Node<T>
{
data = data,
next = head.next
};
head.next = newNode;
}
public T Pop()
{
var popNode = head.next;
if (popNode == tail)
throw new Exception("Stack is empty");
var ret = popNode.data;
head.next = popNode.next;
return ret;
}
public T Top()
{
var popNode = head.next;
if (popNode == tail)
throw new Exception("Stack is empty");
return popNode.data;
}
public bool IsEmpty()
{
return head.next == tail;
}
public void PrintNode()
{
Console.Write("HEAD->");
for (var tempNode = head.next; tempNode != tail; tempNode = tempNode.next)
{
Console.Write(tempNode.data + "->");
}
Console.WriteLine("TAIL");
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment