在java中已知两个非降序链表序列S1与S2,设计函数构造出S1与S2合并后的新的非降序链表S3。 要求S3中没有重复元素。帮我写代码
时间: 2024-06-16 12:04:39 浏览: 105
在Java中,可以通过以下代码实现合并两个非降序链表S1和S2,并构造出新的非降序链表S3,要求S3中没有重复元素:
```java
class ListNode {
int val;
ListNode next;
ListNode(int val) {
this.val = val;
}
}
public class MergeLinkedList {
public static ListNode merge(ListNode s1, ListNode s2) {
if (s1 == null) {
return s2;
}
if (s2 == null) {
return s1;
}
ListNode dummy = new ListNode(0);
ListNode current = dummy;
while (s1 != null && s2 != null) {
if (s1.val < s2.val) {
current.next = s1;
s1 = s1.next;
} else if (s1.val > s2.val) {
current.next = s2;
s2 = s2.next;
} else {
// 如果两个节点的值相等,则只取一个节点,避免重复元素
current.next = s1;
s1 = s1.next;
s2 = s2.next;
}
current = current.next;
}
// 将剩余的节点连接到合并后的链表末尾
if (s1 != null) {
current.next = s1;
}
if (s2 != null) {
current.next = s2;
}
return dummy.next;
}
public static void main(String[] args) {
// 示例测试
ListNode s1 = new ListNode(1);
s1.next = new ListNode(3);
s1.next.next = new ListNode(5);
ListNode s2 = new ListNode(2);
s2.next = new ListNode(4);
s2.next.next = new ListNode(6);
ListNode s3 = merge(s1, s2);
// 输出合并后的链表S3
while (s3 != null) {
System.out.print(s3.val + " ");
s3 = s3.next;
}
}
}
```
阅读全文