How to implement Stack using linked list

Stacks are easier to implement using linked lists. There is no need to set a limit on the size of the stack

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace LinkedlistUsingStack
{
    public class Node
    {
        public int Data { get; set; }
        public Node Next { get; set; }
        public Node(int data)
        {
            this.Data = data;
        }
    }
    public class Stack
    {
        private Node _stackTop;

        public void Push(int newValue)
        {
            Node newNode = new Node(newValue);

            newNode.Next = _stackTop;
            _stackTop = newNode;

        }
        public bool IsEmpty()
        {
            return _stackTop == null;
        }
        public int Pop()
        {
            Node temp = _stackTop;
            var data = temp.Data;
            _stackTop = temp.Next;
            return data;
        }
        public void Print()
        {
            Node current = _stackTop;
            while (current != null)
            {
                Console.WriteLine(current.Data);
                current = current.Next;
            }
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            Stack st = new Stack();
            st.Push(1);
            st.Push(2);
            st.Push(3);
            Console.WriteLine("Before Pop");
            st.Print();
            st.Pop();
            st.Pop();
            Console.WriteLine(st.IsEmpty());
            Console.WriteLine("After Pop");
            st.Print();
        }
    }
}

No comments:

Post a Comment