Kth Node From Middle
unknown
plain_text
a year ago
1.3 kB
2
Indexable
Never
/** * Definition for singly-linked list. * class ListNode { * public int val; * public ListNode next; * ListNode(int x) { val = x; next = null; } * } */ public class Solution { public int lenLL(ListNode A){ ListNode curr = A; int length = 0; while(curr != null){ length++; } return length; } public int solve(ListNode A, int B) { int N = lenLL(A); int midPos = (N / 2) + 1; ListNode curr = A; int pos = 1; while(curr != null){ if(pos == midPos){ curr.next = null; break; } else{ pos++; curr = curr.next; continue; } } int finalVal = 0; int actualPos = midPos - B; if(actualPos > 0){ int pos2 = 0; ListNode curr2 = A; while(curr2 != null){ if(actualPos == pos2){ finalVal = curr2.val; break; } else{ curr2 = curr2.next; pos2++; } } } else{ finalVal = -1; } return finalVal; } }