Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

java code merge-two-sorted-list.md #2017

Merged
merged 1 commit into from
Nov 10, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
}
}

```
Loading