作者helenus (就是爱SEX)
看板java
标题[问题] 把两个linkedlist合并成一个
时间Sun May 7 12:01:00 2006
就是建立两个linked-list 然後可以让人用键盘输入数字
比如说第一个linked-list输入 1 4 7三个数字
第二个linked-list输入 2 5 6三个数字
接着萤幕上会显示出合并後的数字1 2 4 5 6 7
并且把最大的数值7也显示出来
(底下是我写的code 如果有改进的地方也请大家跟我说 谢谢)
=======linkedlist部分=======
class Node
{
int data; //节点资料
Node next; //下一个节点
//建构子
public Node(int data)
{
this.data = data;
this.next = null;
}
}
//串列类别
public class LinkedList
{
private Node first;
private Node last;
//检查串列是否是空的
public boolean isEmpty()
{
return first == null;
}
//在串列插入节点
public void insert(int data, boolean isFront)
{
//建立节点
Node newNode = new Node(data);
//插入节点在开头
if(this.isEmpty())
{
//第一个节点
first = newNode;
last = newNode;
}
else
{
if(isFront)
{
newNode.next = first;
first = newNode;
}
else
{
//新增在节尾
last.next = newNode;
last = newNode;
}
}
}
//找寻节点资料
public boolean find(int data)
{
boolean isFound = false;
Node current = first;
while(current != null)
{
if(data == current.data)
isFound = true;
current = current.next; //下一个节点
}
return isFound;
}
//从前面取得节点的资料
public int fetch(boolean isFront)
{
int data = -1;
if(!this.isEmpty())
{
if(first == last)
{
//只有一个节点
data = first.data;
first = null;
last = null;
}
else
{
if(isFront)
{
//从开头取出
data = first.data;
first = first.next;
}
else
{
Node current = first;
Node temp = last;
//找到最後节点的前一个节点
while(current.next != last)
current = current.next;
last = current;
current.next = null;
data = temp.data;
}
}
}
return data;
}
//串列走访列印所有节点
public void print()
{
if(this.isEmpty())
{
System.out.println("串列是空的");
return;
}
Node current = first;
while(current != null)
{
System.out.print("[" + current.data +"]");
current = current.next; //下一个节点
}
System.out.println();
}
}
=========test部分========
import java.io.*;
public class test1013
{
//主程式
public static void main(String[] args) throws Exception
{
//建立串列物件
LinkedList list = new LinkedList();
LinkedList list1 = new LinkedList();
//插入节点第一个linkedlist
System.out.println("请输入第一个linkedlist的数字三个:");
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String str1 = br.readLine();
String str2 = br.readLine();
String str3 = br.readLine();
int num1 = Integer.parseInt(str1);
int num2 = Integer.parseInt(str2);
int num3 = Integer.parseInt(str3);
list.insert(num1, false);
list.insert(num2, false);
list.insert(num3, false);
System.out.print("第一个linkedlist原始串列:");
list.print();
//插入节点第二个linkedlist
System.out.println("请输入第二个linkedlist的数字三个:");
BufferedReader br1 = new BufferedReader(new InputStreamReader(System.in));
String str4 = br1.readLine();
String str5 = br1.readLine();
String str6 = br1.readLine();
int num4 = Integer.parseInt(str4);
int num5 = Integer.parseInt(str5);
int num6 = Integer.parseInt(str6);
list1.insert(num4, false);
list1.insert(num5, false);
list1.insert(num6, false);
System.out.print("第二个linkedlist原始串列:");
list1.print();
(我想问一下 写到这里我应该怎麽把两个linkedlist合并成一个
由小到大的串列呢?)
}
}
--
※ 发信站: 批踢踢实业坊(ptt.cc)
◆ From: 220.139.56.169
※ 编辑: helenus 来自: 220.139.56.169 (05/07 12:02)