How to implement Stack using linked list

In this blog post, I will show you how to implement LinkedList in C# using Stack.

What is LinkedList

As per the Wikipedia
In computer science, a linked list is a linear collection of data elements, whose order is not given by their physical placement in memory. Instead, each item points to the next. It is a data structure consisting of a collection of nodes which together represent a sequence.
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();
        }
    }
}

Please do not post any spam link in the comment box😊

Post a Comment (0)
Previous Post Next Post