public Node IterativeKLastElement(Node head, int k) { if (head == null || k < 0) return null; if (head !=null && k == 0) return head; int count = 0; Node p = head; while(p!=null && count <k-1) { count++; p = p.Next; } if(p==null) { return null; } Node p1 = head; while(p.Next !=null) { p = p.Next; p1 = p1.Next; } return p1; }
public void InsertAtBeginning(ref Node head, int key) { Node n = new Node(key); if(head == null) { head = n; } else { n.Next = head; head = n; } }
public void InsertSort(Node head) { Node p = head; Node temp = null; Node result = null; while (p != null) { temp = p.Next; SortedInsert(ref result, p); p = temp; } head = result; }
public Node MergeLists(Node head1, Node head2) { Node result = null; if(head1 == null) { return head2; } else if( head2 == null) { return head1; } else { Node p1 = head1; Node p2 = head2; if(p1.Key<=p2.Key) { result = p1; result.Next = MergeLists(p1.Next, p2); } else { result = p2; result.Next = MergeLists(p1, p2.Next); } } return result; }
private void SortedInsert(ref Node head, Node p) { if(head == null || head.Key == p.Key) { p.Next = head; head = p; return; } else { Node t = head; while(t.Next!=null && t.Next.Key < p.Key) { t = t.Next; } p.Next = t.Next; t.Next = p; } }
public void SortedInsert(ref Node head, int k) { Node n = new Node(k); SortedInsert(ref head, n); }
public void RecursiveReverse(ref Node head) { if (head == null || head.Next == null) return; Node p = head; Node temp = p.Next; RecursiveReverse(ref temp); p.Next.Next = p; p.Next = null; head = temp; }
public Node RecursiveKLastElement(Node head, ref int count, int K) { if(head == null) { return null; } //Call stops with the last node and only then the count gets incremented for the first time. Node res = RecursiveKLastElement(head.Next, ref count, K); count++; if(count ==K) { return head; } else { return res; } }
public void Print(Node head) { if(head ==null) return; Node p = head; while(p!=null) { Console.WriteLine(p.Key); p = p.Next; } }