题解 | #链表合并#
链表合并
https://www.nowcoder.com/practice/46bda7f0570a47b6b54a29a0a6ae4c27
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 SeqList_Push_Back(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 resver(ListNode head1,ListNode head2){ if(head1==null&&head2==null){ return null; } if(head1==null&&head2!=null){ return head2; } if(head2==null&&head1!=null){ return head1; } ListNode Node = new ListNode(-1); ListNode prev =head1; ListNode cur = head2; ListNode tmp =Node; while(cur!=null&&prev!=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){ if(head==null){ return; } ListNode tail = head; while(tail!=null){ System.out.print(tail.val+" "); tail=tail.next; } } } public class Main { public static void creat(String s,MySeqList rea){ String[] str = s.split(" "); int a=0; for(int i=0;i< str.length;i++){ a = Integer.parseInt(str[i]); rea.SeqList_Push_Back(a); } } public static void main(String[] args) { Scanner in = new Scanner(System.in); MySeqList myseqlist = new MySeqList(); MySeqList myseqlist1 = new MySeqList(); MySeqList myseqlist2 = new MySeqList(); String s = in.nextLine(); String s1 = in.nextLine(); creat(s,myseqlist); creat(s1,myseqlist1); MySeqList.ListNode tmp= myseqlist.resver(myseqlist.head,myseqlist1.head); myseqlist2.Draw(tmp); } }
本质还是单链表的反转,但需要自己输入值构建链表。自己第一次做的时候反转的代码已经写好了,但往进输入数字的时候总处理不好,卡了很长时间。