已知两个非降序链表序列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部分有很多重复代码,需要优化。