Insert in Sorted way in a Sorted DLL | Linked Lists | MEDIUM

  Рет қаралды 32

Gale Praveen

Gale Praveen

Күн бұрын

Пікірлер: 2
@galepraveen
@galepraveen 15 күн бұрын
Node* sortedInsert(Node* head, int x) { Node* newNode = getNode(x); // case -1, x < head->data if(x < head->data){ newNode->next = head; head->prev = newNode; return newNode; } // case-2, x lies in between Node* prevNode = head, *currNode = head->next; while(currNode != NULL){ if(prevNode->data next = newNode; newNode->prev = prevNode; newNode->next = currNode; currNode->prev = newNode; return head; } prevNode = currNode; currNode = currNode->next; } prevNode->next = newNode; newNode->prev = prevNode; return head; }
@galepraveen
@galepraveen 15 күн бұрын
Solved using Binary search too, if you’d like to see the code and learn…Here it is: Node* getTail(Node* head){ while(head->next){ head = head->next; } return head; } Node* getMidNode(Node* start, Node* end){ if(!start || start == end) return start; Node* slow = start, *fast = start; while(fast != end){ slow = slow->next; fast = fast->next; if(fast != end) fast = fast->next; } return slow; } class Solution { public: Node* sortedInsert(Node* head, int x) { Node* newNode = getNode(x); if(x < head->data){ newNode->next = head; head->prev = newNode; return newNode; } Node* start = head, *end = getTail(head); if(x > end->data){ end->next = newNode; newNode->prev = end; return head; } // Node* mid = getMidNode(start, end); // cout data prev; } } // // cout next = end; return head; }
Make array elements unique | Sorting | MEDIUM
13:15
Gale Praveen
Рет қаралды 35
Walking on LEGO Be Like... #shorts #mingweirocks
00:41
mingweirocks
Рет қаралды 7 МЛН
ЛУЧШИЙ ФОКУС + секрет! #shorts
00:12
Роман Magic
Рет қаралды 34 МЛН
Random Emoji Beatbox Challenge #beatbox #tiktok
00:47
BeatboxJCOP
Рет қаралды 64 МЛН
Split array in three equal sum subarrays | Arrays | MEDIUM
19:35
Second Largest | Arrays | EASY
9:50
Gale Praveen
Рет қаралды 14
Remove Duplicates In Array | Arrays | EASY
23:57
Gale Praveen
Рет қаралды 33
Minimum sum | Arrays | MEDIUM
14:09
Gale Praveen
Рет қаралды 17
Triplet Family | Arrays | EASY
11:50
Gale Praveen
Рет қаралды 76
Rotate by 90 degree | Matrices | MEDIUM
9:48
Gale Praveen
Рет қаралды 15
36 Blind 75 | Course Schedule | Explained with BFS & DFS
46:51
Walking on LEGO Be Like... #shorts #mingweirocks
00:41
mingweirocks
Рет қаралды 7 МЛН