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 def getNode(llist, positionFromTail): # Write your code here last_index = llist for _ in range(positionFromTail): last_index = last_index.next desire_position = llist while last_index.next: last_index = last_index.next desire_position = desire_position.next return desire_position.data
+ 0 comments here's my C++ solution. If we can get the length of the linked list, we can get that position form the head. Why? Because I'm initially given the head pointer so I just have to count certain number from that head.
int getNode(SinglyLinkedListNode* llist, int positionFromTail) { int LSize = 0; SinglyLinkedListNode* counter = llist; while(counter) { ++LSize; counter = counter->next; } int positionFromHead = LSize - positionFromTail; while (positionFromHead-- > 1) { llist = llist->next; } return llist->data; }
+ 0 comments Javascript Solution using Recursion. Time complexity O(N). No Arrays
function getNode(llist, positionFromTail) { let counter = 0; let flag = false; let res = null; function recur(llist,positionFromTail,flag){ if(llist && !flag){ recur(llist.next,positionFromTail,flag) counter += 1; if(counter == positionFromTail+1) { res = llist.data; flag = true; } } } recur(llist,positionFromTail) return res; }
+ 0 comments Python3 soln:
def getNode(llist, positionFromTail): """ find length of list position from head = length - position from tail iterate again, if traversals = position, print value """ length, traversals = 0,0 current = llist while current: length += 1 current = current.next positionFromHead = length-positionFromTail-1 for i in range(positionFromHead): llist = llist.next return llist.data
+ 0 comments javascript code:
function getNode(llist, positionFromTail) { let data; let curr = llist for(let i = 0;i<positionFromTail;i++){ curr = curr.next; } if(curr.next){ llist = llist.next while(curr.next){ data = llist.data; curr = curr.next; llist = llist.next } return data } return llist.data }
Load more conversations
Sort 885 Discussions, By:
Please Login in order to post a comment