Stack Push Operation on Link List C#

Now i will be presenting the implementation  of stack on linked list.

Every body would be aware of coding stack on arrays which is a very simple step. But some people find difficulty while implementing the stack on link list.
First you should know what is a stack, Stack or LIFO Stack (last in first out) is a type of data structure which is use to put the values in a proper from and is implemented in various computer programs, It contains one entry and exit point from where values can push in or pop out of the Stack.
*/for more details on stack you can view stack description at (www.farazashraf.wordpress.com/stack)*/

Link List is also another form of data structure which contains item and it’s linking next node.
*/for more details on stack you can view stack description at (www.farazashraf.wordpress.com/linklist)*/

So i will implementing the stack push operation in link list.
It will be done through a C# class which i have named test_Stack.
It contains the private variable first which will be null.
A private inner class Node is used to declare string item and next node.
A bool method is just used to check if the first node is empty .

class test_Stack
    {
        private Node first = null;
        private class Node
        {
            public string item ;
            public Node next;
        }
       public bool check()
        {
            return first == null;
        }
       public void push(string item)
        {
            Node oldfirst = first;
            first = new Node();
            first.item = item;
            first.next = oldfirst;
        
        }
You can call the method in the main function to check if the class is working fine. By just creating an object and calling the method.

static void Main(string[] args)
        {
            test_Stack test1 = new test_Stack();
            string item=null;
            int i=2;
            while (i != 0)
            {
                Console.WriteLine(“enter the test value”);
                item = Console.ReadLine();
                test1.push(item);
                i–;
            }
       

Advertisements