forked from laviii123/Btecky
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request laviii123#235 from kushal34712/patch-4
Create squdrequst799
- Loading branch information
Showing
1 changed file
with
32 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,32 @@ | ||
//// | ||
|
||
|
||
|
||
class Solution { | ||
Node sortedInsert(Node head1, int key) { | ||
// Step 1: Create a new node with the given key. | ||
Node newNode = new Node(key); | ||
|
||
// If the linked list is empty or the key is smaller than or equal to the head's data, | ||
// insert the new node at the beginning. | ||
if (head1 == null || key <= head1.data) { | ||
newNode.next = head1; | ||
return newNode; | ||
} | ||
|
||
// Step 2: Traverse the linked list to find the correct position. | ||
Node current = head1; | ||
Node prev = null; | ||
while (current != null && current.data < key) { | ||
prev = current; | ||
current = current.next; | ||
} | ||
|
||
// Step 3: Insert the new node at the correct position. | ||
prev.next = newNode; | ||
newNode.next = current; | ||
|
||
// Step 4: Return the head of the modified linked list. | ||
return head1; | ||
} | ||
} |