• 两个有序链表的合并


    已知两个非降序链表序列S1与S2,设计函数构造出S1与S2合并后的新的非降序链表S3。

    一手编的第一个程序啊啊,好多小错误,调试了好久,不上手真的会忽视掉好多细节。。


    import java.util.*;

    class Node{ //结点类
     public int data;
     Node next = null;
     public Node(int data) {
      this.data = data;
     }
    }

    public class Solution {

     public static class  Link{ //链表类
      Node head = null;
      Node tem = null; 
      
      public void addnode(int d) {
       Node n = new Node(d);
       if(head == null)
        {head = n;
        tem = head;
        return;}
       tem.next = n;
       while(tem.next != null)//确保tem在链尾
        tem = tem.next;
        }
      
      public Link merge(Link a, Link b) {
       a.tem = a.head;
       b.tem = b.head;
       Link c = new Link();
       
       while(a.tem != null && b.tem != null) {
        if(a.tem.data<=b.tem.data) {
         c.addnode(a.tem.data);
         a.tem = a.tem.next;
        }
        else{
         c.addnode(b.tem.data);
         b.tem = b.tem.next;
        }
       }
       while(a.tem != null) { 
        c.addnode(a.tem.data);
        a.tem = a.tem.next;
       }
       while(b.tem != null) {
        c.addnode(b.tem.data);
        b.tem = b.tem.next;
       }
       return c;
      }
      public void print(Link d) {
       d.tem = d.head;
       if(d.tem == null)
       {System.out.println("null");}
       else{
         while(d.tem.next != null) {
         System.out.print(d.tem.data +" ");
         d.tem = d.tem.next;
            }
         System.out.print(d.tem.data);
       }
      }
     }

     
     
     public static void main(String[] args) {
      Scanner in = new Scanner(System.in);

      Link s1 = new Link();
      Link s2 = new Link();
      
      int count;
      do {
      count = in.nextInt();
      if(count != -1)
       s1.addnode(count);
      }while(count != -1);
       
      do {
       count = in.nextInt();
       if(count != -1)
        s2.addnode(count);
       }while(count != -1);
      
      Link s3 = new Link().merge(s1, s2);
      
      new Link().print(s3);
       
      
      in.close();
       }
     }

    最终结果在大规模输入时内存超限,确实merge部分有很多重复代码,需要优化。

  • 相关阅读:
    GC选择之CMS 并发标记清除
    JVM内存概览与GC初步
    Shell 判断语句
    SUID SGID
    maven package
    ACL权限控制列表
    账户与密码管理
    Ubuntu与Centos在登陆安全方面的比较
    【PL/SQL Developer】动态执行表不可访问,本会话的自动统计被禁止
    【Centos7】Delete virtual bridge
  • 原文地址:https://www.cnblogs.com/dyq19/p/10256125.html
Copyright © 2020-2023  润新知