public void Push(Node node) { if (node == null) throw new ArgumentNullException("node"); node.Next = Head; Head = node; }
public static void Traverse(Node head) { if (head == null) return; Console.Write("{0}->", head.Value); Traverse(head.Next); }
public Node Pop() { if (IsEmpty()) return null; Node node = Head; Head = Head.Next; return node; }
public static Node Reverse(Node head) { var input = new Stack(head); var output = new Stack(null); while (!input.IsEmpty()) { output.Push(input.Pop()); } return output.Head; }
public void Add(Object item) { Node newNode = new Node(item); if (headNode == null) { headNode = newNode; } else { Node currentNode = headNode; while (currentNode.nextNode != null) { currentNode = currentNode.nextNode; } currentNode.nextNode = newNode; } }
static void Main() { var a = new Node("A"); var b = new Node("B"); var c = new Node("C"); var d = new Node("D"); a.Next = b; b.Next = c; c.Next = d; var input = a; Console.Write("Input:\t"); SingleLinkedList.Traverse(input); Console.WriteLine(); Node output = SingleLinkedList.Reverse(input); Console.Write("Output:\t"); SingleLinkedList.Traverse(output); Console.WriteLine(); }
public Node(Object item) { this.item = item; nextNode = null; }
public void Reverse() { Node previousNode; Node currentNode; Node nextNode; previousNode = headNode; currentNode = headNode.nextNode; headNode.nextNode = null; while (currentNode.nextNode != null) { // temporarily store the next node, or else we'll lose it when we change the pointer nextNode = currentNode.nextNode; // change the next node pointer to the previous node currentNode.nextNode = previousNode; // previous node is now the current node previousNode = currentNode; // current node is now the next node that was stored temporarily currentNode = nextNode; // at this point we've moved onto the next node } headNode = currentNode; headNode.nextNode = previousNode; }
public LinkedList() { headNode = null; }
public Stack(Node head) { Head = head; }