Skip to content

Instantly share code, notes, and snippets.

@Ram-1234
Last active December 30, 2020 14:44
Show Gist options
  • Save Ram-1234/45f7d66493990aecce2ccb7d197302ba to your computer and use it in GitHub Desktop.
Save Ram-1234/45f7d66493990aecce2ccb7d197302ba to your computer and use it in GitHub Desktop.
AMAZON LINKED LIST PROBLEM
Problem Description:-
Given a linked list A of length N and an integer B.
You need to find the value of the Bth node from the middle towards the beginning of the Linked List A.
If no such element exists, then return -1.
NOTE:-Position of middle node is: (N/2)+1, where N is the total number of nodes in the list.
Problem Constraints
1:-1 <= N <= 105
2:-1<= Value in Each Link List Node <= 103
3:-1 <= B <= 105
INPUT:- A = 3 -> 4 -> 7 -> 5 -> 6 -> 1 6 -> 15 -> 61 -> 16
B = 3
OUTPUT:-4
##CODE IN JAVA
/**
* 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 solve(ListNode A, int B) {
ListNode curr=A;
int i=0;
int pos=0;
boolean f=false;
while(curr!=null){
i++;
curr=curr.next;
}
ListNode curr1=A;
int mid=(int) i/2 +1;
if(B<=mid && i>1){
//int mid=(int) i/2 +1;
if(mid==B){
int m=B-1;
while(m-->0){
curr1=curr1.next;
}
return curr1.val;
}
else if(mid<B){
int m=B-1;
while(m++<B){
curr1=curr1.next;
}
return curr1.val;
}
else{
int m=mid-B-1;
while(m-->0){
curr1=curr1.next;
}
return curr1.val;
}
}
else
return -1;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment