We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
Get Node Value
Get Node Value
+ 0 comments My Python solution with recursion:
rslt, counter = 0, -1 def getNode(llist, positionFromTail, x = 0): global rslt, counter #Recursion to start at the end of the list (var x equals n at the nth node): x += 1 if llist.next != None: getNode(llist.next, positionFromTail, x) #This part is executed once we reach the final node and then for each previous one (counter equals 0 at end and +=1 at each previous node): counter += 1 if positionFromTail == counter: rslt = llist.data #Here we reset the global counter once we reach the head of the list: if x == 1: counter = -1 return rslt
+ 0 comments c++ solution:
int getNode(SinglyLinkedListNode* llist, int p) { stack<int> a; while (llist!=nullptr) { a.push(llist->data); llist = llist->next; } while (p>0) { a.pop(); p--; } return a.top(); }
+ 0 comments Java 15:
public static int getNode(SinglyLinkedListNode llist, int positionFromTail) { SinglyLinkedListNode iterator = llist; SinglyLinkedListNode result = llist; while(iterator.next != null && positionFromTail > 0) { positionFromTail--; iterator = iterator.next; } while(iterator.next != null) { iterator = iterator.next; result = result.next; } return result.data; }
+ 0 comments SCALA, COMPILE ERROR
val result = getNode(llist.head, position)
should beval result = Result.getNode(llist.head, position)
+ 0 comments JS code :
function getNode(llist, positionFromTail) { let current = llist; let reverse = null; let temp = null; if(!llist) return llist; while(current !== null){ temp = current.next; current.next = reverse; reverse = current; current = temp; } let currentIndex = 0; let current2 = reverse; while(current2 !== null){ if(currentIndex === positionFromTail) break; currentIndex++; current2 = current2.next; } return current2.data; }
Load more conversations
Sort 906 Discussions, By:
Please Login in order to post a comment