Posts

Showing posts with the label linked-list

How to Insert a node into alternating linked list after the current node?

Image
Clash Royale CLAN TAG #URR8PPP How to Insert a node into alternating linked list after the current node? I am writing a linked list function that alternates the nodes odd/even.For example if the input was 6->7->5->3->6->2->9->1 it would output 6->7->6->5->2->3->5->9->1 . The issue I am having is when I run my code I get 6->6->7->2->5->3->5->9->1 .I know the issue stems from the node being inserted before the 7. When it should be inserted after the 7. However, I can't seem to figure out how this is done. How would I go about inserting it after the 7? 6->7->5->3->6->2->9->1 6->7->6->5->2->3->5->9->1 6->6->7->2->5->3->5->9->1 Here is a copy of my function. I am pretty for sure the issue is in the final if loop. void InterleaveOddsAndEvensInOrigOrder(Node*& headPtr) { if(headPtr ==0 || headPtr->link == 0) { cout << ...

Improvement in linklist intersection point program

Image
Clash Royale CLAN TAG #URR8PPP Improvement in linklist intersection point program I have written below code for finding intersection point of linklist. Can somebody please review the same and tell me is there any improvement I can do to make it better. Algo-: If at any point p1 meets p2, then p1/p2 is the intersection node. int getIntesectionNode(struct Node* head1, struct Node* head2) { struct Node *start1 = head1; struct Node *start2 = head2; bool endFound1 = false; bool endFound2 = false; if( start1 == NULL || start2 == NULL) { return -1; } while(1) { start1 = start1->next; start2 = start2->next; if( start1 != start2) { if( start1 == NULL) { if (endFound1) { printf("Intersection not found !"); break; } start1 = head2; endFound1 = true; } if( start2 == NULL) { if (endFound2 ) { printf("Intersection not found !"); ...

Is the space complexity of a recursive algorithm necessarily at least as large as the depth of the recursive call?

Image
Clash Royale CLAN TAG #URR8PPP Is the space complexity of a recursive algorithm necessarily at least as large as the depth of the recursive call? I am having trouble determining when recursive functions are sub-optimal to their iterative counterparts when space is an issue. When writing recursive functions, is the space complexity necessarily at least as large as the depth of the recursive call if it is not tail recursive? For example, lets remove duplicates from a linked list using recursion. This can be done trivially with an iterative approach in O(n^2) time and O(1) space. But is the recursive variant also O(1) space? removeDuplicatesRecursive() { let current = this.head; while (current.next) { if (this.head.data === current.next.data) { current.next = current.next.next } else { current = current.next; } } if (this.head.next) { removeDuplicatesRecursive(this.head.next); } return head; } Yo...