/// <summary> /// Write code to reverse a linked list, if you able to do it using loops, try to solve with recursion? /// </summary> static void Ex15() { SLinkedList list = new SLinkedList(); list.AddBeginning(list, 10); list.AddBeginning(list, 9); list.AddBeginning(list, 1); list.AddBeginning(list, 12); list.AddBeginning(list, 13); Node current = list.start; Node temp = current; Node next = current.next; while (current != null) { current = next; next = current.next; current.next = temp; temp = current; } list.start = temp; for (Node node = list.start; node != null; node = node.next) { Console.WriteLine(node.data); } }
public void AddBeginning(SLinkedList list, int data) { Node newNode = new Node(data); newNode.next = list.start; list.start = newNode; }
public Node LastNode(SLinkedList list) { Node current = list.start; while (current.next != null) { current = current.next; } return(current); }
public void AddEnd(SLinkedList list, int data) { Node newNode = new Node(data); if (list.start == null) { list.start = newNode; return; } Node lastNode = LastNode(list); lastNode.next = newNode; }
/// <summary> /// How to find the 3rd element from the end, in a singly linked, in a single pass? /// </summary> static void Ex11() { SLinkedList list = new SLinkedList(); list.AddEnd(list, 10); list.AddEnd(list, 9); list.AddEnd(list, 1); list.AddEnd(list, 12); list.AddEnd(list, 13); Node current = list.start; while (current.next.next.next != null) { current = current.next; } Console.WriteLine($"The 3rd element from the end is: {current.data}"); }