已知兩個非降序鏈表序列S1與S2,設計函數構造出S1與S2合併後的新的非降序鏈表S3。 一手編的第一個程式啊啊,好多小錯誤,調試了好久,不上手真的會忽視掉好多細節。。 import java.util.*; class Node{ //結點類 public int data; Node next = ...
已知兩個非降序鏈表序列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 int finddata(Node d) {
return d.data;
}
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.finddata(a.tem)<=b.finddata(b.tem)) {
c.addnode(a.finddata(a.tem));
a.tem = a.tem.next;
}
else{
c.addnode(b.finddata(b.tem));
b.tem = b.tem.next;
}
}
while(a.tem != null) {
c.addnode(a.finddata(a.tem));
a.tem = a.tem.next;
}
while(b.tem != null) {
c.addnode(b.finddata(b.tem));
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();
}
}
1.最初寫finddata的輸入時只寫了tem,結果會發生NullPointerException 空指針異常;
2.在賦值給c的時候,最初寫的是c.tem.data = a.finddata.
兩個錯誤的本質都是對鏈表的理解還不深,只有創建結點才能賦值,每一個鏈表都有單獨的引用。
3.最終結果在大規模輸入時記憶體超限,確實merge部分有很多重覆代碼,需要優化。