Get Node Value
Get Node Value
salcio + 0 comments Hi,
I think I found quite nice soution - no recursion, no arrays. We iterate only once through whole list.
int GetNode(Node *head,int positionFromTail) { int index = 0; Node* current = head; Node* result = head; while(current!=NULL) { current=current->next; if (index++>positionFromTail) { result=result->next; } } return result->data; }
RodneyShag + 0 comments O(1) space complexity Java Iterative solution.
From my HackerRank solutions.
I use the "runner" technique. We make a runner pointer move k elements into the list. Then we create a curr pointer. We move both pointers 1 step at a time until runner is at the end. When this happens, curr will be at the kth to last element.
Runtime: O(n)
Space Complexity: O(1)int GetNode(Node head, int k) { Node curr = head; Node runner = head; /* Move runner into the list by k elements */ for (int i = 0; i < k; i++) { runner = runner.next; } /* Move both pointers */ while (runner.next != null) { curr = curr.next; runner = runner.next; } return curr.data; }
Let me know if you have any questions.
onuremreerol + 0 comments Here is another clean and tidy solution in java. If you have any question, feel free to ask.
int GetNode(Node head,int n) { Node temp = head; for (int i = 0; head.next != null; i++) { head = head.next; if ( i >= n) temp = temp.next; } return temp.data; }
shubhamgoyal1101 + 0 comments python 3 code, easy to understand :). I used one pointer to get the length of the list than subtracted position from it and reach the required node via another pointer which was on head of the list.
def GetNode(head, position): count=0 second_head = head while head.next: head=head.next count+=1 for i in range(count-position): second_head=second_head.next return second_head.data
__spartax + 0 comments hii friends this is my solution
def GetNode(head, position): stk = [] t = head while t: stk = [t.data] + stk t = t.next return stk[position]
Sort 653 Discussions, By:
Please Login in order to post a comment