For queues, we append new node at the tail end, and the tail take on its next.
The head pointer stays in place at the first node. When we execute something, we pop from the queue, and the head moves to next.
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 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 |
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 Queue { private Node head; //head points to the beginning of the queue. We pop by using the head. private Node tail; //tail points to the end of the queue. We append using the tail // public void push(Object newData) { if((head == null) && (tail == null)) { head = tail = new Node(newData, null); Console.WriteLine("+ pushed {0} onto the Queue", newData); return; } tail.next = new Node(newData, null); tail = tail.next; Console.WriteLine("+ pushed {0} onto the Queue", newData); } public void pop() { if(head != null) { Node toRemove = head; head = head.next; Console.WriteLine("- popped {0} onto the Queue", toRemove.data); toRemove.data = null; toRemove.next = null; } else { Console.WriteLine("Can't pop anymore, Queue 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"); GBTU g = new GBTU(); g.BTech(); //reference type LinkedList Queue myList = new Queue(); myList.push("Ricky"); myList.push("Lily"); myList.push("Sophia"); myList.print(); myList.pop(); myList.print(); myList.pop(); myList.pop(); myList.print(); myList.pop(); } } |