Skip to content

Commit

Permalink
Merge pull request #233 from RK-41/create/gfg-potd-31-oct-2024
Browse files Browse the repository at this point in the history
Create GFG_POTD_31_OCT_2024.cpp
  • Loading branch information
Gyanthakur authored Oct 31, 2024
2 parents c70828c + 5b12ee0 commit f72f184
Showing 1 changed file with 116 additions and 0 deletions.
116 changes: 116 additions & 0 deletions october_2024/GFG_POTD_31_OCT_2024.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,116 @@
/*
Problem
Given a sorted doubly linked list and an element x, you need to insert the element x into the correct position in the sorted Doubly linked list(DLL).
Note: The DLL is sorted in ascending order
*/

//{ Driver Code Starts
#include <bits/stdc++.h>
using namespace std;

struct Node {
int data;
struct Node *prev, *next;
};

struct Node* getNode(int data) {
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->data = data;
newNode->prev = newNode->next = NULL;
return newNode;
}

void printList(struct Node* head) {
while (head != NULL) {
cout << head->data << " ";
head = head->next;
}
cout << endl;
}


// } Driver Code Ends
/*structure of the node of the DLL is as
struct Node {
int data;
struct Node* prev, *next;
};
*/
// function should insert a new node in sorted way in
// a sorted doubly linked list
// Return the head after insertion
class Solution {
public:
Node* sortedInsert(Node* head, int x) {
// Code here
// 31.10.24 POTD
if(!head){
Node* nd = new Node;
nd->data = x;
return nd;
}

Node* h=head, *prev=NULL;

while(h && x>h->data){
prev = h;
h = h->next;
}

Node* nd = new Node;
nd->data = x;
nd->next = h;
if(prev){
nd->prev = prev;
prev->next = nd;
}
if(h) h->prev = nd;

if(!prev) head = nd;

return head;
}
};


//{ Driver Code Starts.

int main() {
int t;
cin >> t;
cin.ignore(); // Ignore the newline character after t

while (t--) {
string input;
getline(cin, input); // Read the entire line for the array elements

stringstream ss(input);
Node *head = nullptr, *tail = nullptr;
int x;

if (ss >> x) {
head = getNode(x);
tail = head;
}

while (ss >> x) {
tail->next = getNode(x);
tail->next->prev = tail;
tail = tail->next;
}

int valueToInsert;
cin >> valueToInsert;
cin.ignore(); // Ignore the newline character after the value

Solution obj;
head = obj.sortedInsert(head, valueToInsert);
printList(head);
}

return 0;
}

// } Driver Code Ends

0 comments on commit f72f184

Please sign in to comment.