题解 | #链表合并#

链表合并

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);
    }
}

很简单的一道题

全部评论

相关推荐

不愿透露姓名的神秘牛友
昨天 12:19
点赞 评论 收藏
分享
10-16 22:56
门头沟学院 C++
1234567800:歌尔今年给211开14-15k吗,我本地人连面试都不给😂
点赞 评论 收藏
分享
评论
点赞
收藏
分享
牛客网
牛客企业服务