Kth Node From Middle
Total program, without staticunknown
plain_text
a year ago
3.0 kB
5
Indexable
Never
import java.util.*; import java.io.*; import java.lang.*; class ListNode { int val; ListNode next; ListNode() { } ListNode(int x) { val = x; next = null; } } class Test { public ListNode insertBegin(ListNode head2,int x){ ListNode temp = new ListNode(x); temp.next = head2; return temp; } public int lenLL(ListNode A){ ListNode curr = A; int length = 0; while(curr != null){ curr = curr.next; length++; continue; //curr = curr.next; } System.out.println(length); return length; } public int solve(ListNode A, int B) { ListNode curr = A; int lenOfLL = lenLL(A); int midPos = (lenOfLL / 2) + 1; int pos = 1; while(curr != null){ if(pos == midPos){ curr.next = null; break; } else{ curr = curr.next; pos++; continue; } } ListNode head2 = null; ListNode curr2 = A; while(curr2 != null){ head2 = insertBegin(head2,curr2.val); curr2 = curr2.next; } int finalVal = 0; if(B < pos){ ListNode curr3 = head2; int newPos = 1; while(curr3 != null){ if(newPos == (B + 1)){ finalVal = curr3.val; break; //return curr3.val; } else{ curr3 = curr3.next; newPos++; continue; } } } else if(B >= pos){ finalVal = -1; //return - 1; } return finalVal; } public static void main(String args[]) { ListNode head = new ListNode(630); ListNode temp1 = new ListNode(624); ListNode temp2 = new ListNode(85); ListNode temp3 = new ListNode(955); ListNode temp4 = new ListNode(757); ListNode temp5 = new ListNode(841); ListNode temp6 = new ListNode(967); ListNode temp7 = new ListNode(377); ListNode temp8 = new ListNode(932); head.next = temp1; temp1.next = temp2; temp2.next = temp3; temp3.next = temp4; temp4.next = temp5; temp5.next = temp6; temp6.next = temp7; temp7.next = temp8; int value = solve(head,2); System.out.println(value); //printlist(head); } // public static void printlist(Node head) { // Node curr = head; // while (curr != null) { // System.out.print(curr.data + " "); // curr = curr.next; // } // } }