题解 | #链表合并#
链表合并
https://www.nowcoder.com/practice/27c833289e5f4f5e9ba3718ce9136759
import java.util.Scanner;
class MySeqList{
class ListNode{
public int val;
public ListNode next;
public ListNode(int val){
this.val = val;
}
}
public ListNode head;
public void MySeqList_PushBack(int val){
ListNode Node = new ListNode(val);
if(head==null){
head=Node;
return;
}
ListNode tail=head;
while(tail.next!=null){
tail=tail.next;
}
tail.next=Node;
}
public ListNode Merge(ListNode head1,ListNode head2){
if(head1==null&&head2==null){
return null;
}
if(head1==null&&head2!=null){
return head2;
}
if(head1!=null&&head2==null){
return head1;
}
ListNode Node =new ListNode(0);
ListNode tmp = Node;
ListNode prev = head1;
ListNode cur = head2;
while(prev!=null&&cur!=null){
if(prev.val<cur.val){
tmp.next=prev;
prev = prev.next;
tmp = tmp.next;
}else{
tmp.next=cur;
cur = cur.next;
tmp=tmp.next;
}
}
if(prev!=null){
tmp.next = prev;
}
if(cur!=null){
tmp.next=cur;
}
return Node.next;
}
public void Draw(ListNode head){
ListNode tail = head;
while(tail!=null){
System.out.print(tail.val+" ");
tail = tail.next;
}
}
}
public class Main {
public static void getcreate(MySeqList head,String str){
String[] ret = str.split(" ");
for(int i=0;i<ret.length;i++){
int a = Integer.parseInt(ret[i]);
head.MySeqList_PushBack(a);
}
}
public static void main(String[] args) {
MySeqList mySeqList = new MySeqList();
MySeqList mySeqList2 = new MySeqList();
MySeqList mySeqList1 = new MySeqList();
Scanner scanner = new Scanner(System.in);
String str1 = scanner.nextLine();
String str2 = scanner.nextLine();
getcreate(mySeqList,str1);
getcreate(mySeqList1,str2);
MySeqList.ListNode tmp= mySeqList2.Merge(mySeqList.head,mySeqList1.head);
mySeqList.Draw(tmp);
}
}
很简单的一道题
查看13道真题和解析