Skip to content

Commit

Permalink
java code merge-two-sorted-list.md
Browse files Browse the repository at this point in the history
  • Loading branch information
nishant4500 authored Nov 10, 2024
1 parent 75ec917 commit a811948
Showing 1 changed file with 40 additions and 1 deletion.
41 changes: 40 additions & 1 deletion docs/linked-list/merge-two-sorted-list.md
Original file line number Diff line number Diff line change
Expand Up @@ -79,4 +79,43 @@ public:
return dummy.next; // Return the head of the merged list
}
};
```
```
## Code Implementation

Here’s the JAVA code for merging two sorted linked lists:

```java
class ListNode {
int val;
ListNode next;
ListNode(int x) {
val = x;
next = null;
}
}

class Solution {
public ListNode mergeTwoLists(ListNode list1, ListNode list2) {
ListNode dummy = new ListNode(0); // Dummy node to start the merged list
ListNode tail = dummy;

// Merge the lists by comparing nodes
while (list1 != null && list2 != null) {
if (list1.val < list2.val) {
tail.next = list1;
list1 = list1.next;
} else {
tail.next = list2;
list2 = list2.next;
}
tail = tail.next;
}

// Attach the remaining nodes, if any
tail.next = (list1 != null) ? list1 : list2;

return dummy.next; // Return the head of the merged list
}
}

```

0 comments on commit a811948

Please sign in to comment.