public static ListNode GetKthLastNodeOfTheList(ListNode linkedList, int k) { int currentNodeIndex = 0; // Store list head pointer ListNode kthNode = linkedList; // Corner case if (linkedList == null) { return null; } // Skip first k nodes while ((currentNodeIndex < k) && (linkedList != null)) { linkedList = linkedList.GetNextNode(); currentNodeIndex ++; } // No more nodes left in the list if (linkedList == null) { return null; } // Continue to iterate both pointers to the end of the list while (linkedList != null) { kthNode = kthNode.GetNextNode (); linkedList = linkedList.GetNextNode (); } return kthNode; }
public void Setup() { for (int i = 10; i >= 0; i--) { listHead = new ListNode (i, listHead); } listHead.Print (); }
public static ListNode GetFifthLastNodeOfTheList(ListNode linkedList) { // Return 5th last node from the end of the list return ListManager.GetKthLastNodeOfTheList (linkedList, 5); }
public ListNode(int data, ListNode nextNode) { this.data = data; this.nextNode = nextNode; }
public ListNode() { this.data = 0; this.nextNode = null; }
public void TearDown() { listHead = null; }