Stack appends (or pushes) at the end. And pops at the end also. hence, all we need is one pointer to do that.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 |
using System; public class Program { //create reference type Node public class Node { public Node next; public Object data; public Node(Object newData, Node newNext) { next = newNext; data = newData; } } public class Stack { private Node head; //variable 'head' reference type stores references (addresses) // public void push(Object newData) { head = new Node(newData ,head); } public void pop() { if(head != null) { head = head.next; } else { Console.WriteLine("Can't pop anymore, stack is empty"); } } public void print() { Console.WriteLine("-------- START --------"); for (Node temp = head; temp != null; temp = temp.next) { Console.WriteLine(temp.data); } Console.WriteLine("------ END -------"); } } public static void Main() { Console.WriteLine("Hello World"); //reference type LinkedList Stack myList = new Stack(); myList.push(88); myList.push(99); myList.push(120); myList.print(); myList.pop(); myList.print(); myList.pop(); myList.pop(); myList.print(); myList.pop(); } } |