-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathGFG_POTD3.cpp
47 lines (44 loc) · 1.17 KB
/
GFG_POTD3.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
Question-- >> Insert in a Sorted List
https : // practice.geeksforgeeks.org/problems/insert-in-a-sorted-list/1
Given a linked list sorted in ascending order and an integer called data,
insert data in the linked list such that the list remains sorted.
struct Node
{
int data;
struct Node *next;
Node(int x)
{
data = x;
next = NULL;
}
};
class Solution
{
public:
// Should return head of the modified linked list
Node *sortedInsert(struct Node *head, int data)
{
if (!head || head->data >= data)
{
Node *n = new Node(data);
n->next = head;
return n;
}
Node *temp = head;
while (temp->next && temp->next->data <= data)
{
temp = temp->next;
}
if (temp->next == NULL && temp->data <= data)
{
Node *n = new Node(data);
temp->next = n;
return head;
}
Node *n = new Node(data);
Node *next = temp->next;
temp->next = n;
n->next = next;
return head;
}
};