static void FindStartOfLoop(Node node) { Node slow = node; Node fast = node; while (fast.next != null) { fast = fast.next.next; slow = slow.next; if (slow == fast) break; } if (fast == null) { Console.WriteLine("There is no loop"); return; } Console.WriteLine("Slow/Fast meeting point: {0}", fast.data); slow = node; while (slow != fast && fast != null) { slow = slow.next; fast = fast.next; } Console.WriteLine("Start of loop node: {0}", slow.data); }
public static void GetNthFromEnd(Node node, int n) { if (n <= 0 || node == null) return; Node fast = node; Node slow = node; for (int i = 0; i < n; i++) { if (fast != null) fast = fast.next; else { Console.WriteLine("Invalid n"); return; } } while (fast != null) { fast = fast.next; slow = slow.next; } Console.WriteLine("Nth from last = {0}", slow.data); }
public static void printList(Node node) { Console.Write("List: "); while (node != null) { Console.Write("{0} ", node.data); node = node.next; } }
static void deleteNode(Node n) { if (n == null || n.next == null) return; if (n.next != null) { n.data = n.next.data; n.next = n.next.next; } }
public Node buildList(int size) { Node cur; for (int i = size; i >= 1; i--) { cur = new Node(i); cur.next = head; head = cur; } return head; }
public Node buildList(int[] arr) { Node cur; foreach (int i in arr) { cur = new Node(i); cur.next = head; head = cur; } return head; }
static void RemoveDuplicates(Node node) { if (node == null) return; HashSet<int> hs = new HashSet<int>(); hs.Add(node.data); while (node.next != null) { if (hs.Contains(node.next.data)) { node.next = node.next.next; } else { node = node.next; hs.Add(node.data); } } }
static Node AddLists(Node a, Node b) { Node dummy = new Node(-1); Node sum = dummy; int carry = 0; while (a != null && b != null) { int val = a.data + b.data + carry; Node cur = new Node(val % 10); carry = val / 10; sum.next = cur; sum = cur; a = a.next; b = b.next; } while (a != null) { int val = a.data + carry; Node cur = new Node(val % 10); carry = val / 10; sum.next = cur; sum = cur; a = a.next; } while (b != null) { int val = b.data + carry; Node cur = new Node(val % 10); carry = val / 10; sum.next = cur; sum = cur; b = b.next; } if (carry > 0) sum.next = new Node(carry); return dummy.next; }
public Node(int data, Node next) { this.data = data; this.next = next; }