我在java.Now中设计了我自己的单链表数据结构,我将要定义一个具有特定行为的函数。我将这个函数命名为“PurgeList”。该函数应该删除每个重复的节点相同的内容),并且至少我希望列表本身只保留一个包含该内容的节点。例如,如果节点中保存的当前内容是顺序的:如何从链表中删除重复的节点?
1,2,3 ,4,1,4,5
与所提到的行为的函数执行后,该列表必须塑造成:
1,2,3,4,5
例代码:
1-类节点
public class Node {
Object Element;
Node Link;
public Node() {
this(null,null);
}
public Node(Object Element, Node Link) {
this.Element = Element;
this.Link = Link;
}
}
2-班级列表
import java.util.Scanner;
public class List {
int Size;
Node FirstNode;
Scanner UserInfo = new Scanner(System.in);
Scanner UserInput = new Scanner(System.in);
Node LastNode;
public List() {
FirstNode = null;
Size = 1;
}
public void PurgeList() {
Node temp1 = FirstNode;
while (temp1 != null) {
Node temp2 = temp1;
while (temp2.Link != null)
if (temp1.Element.equals(temp2.Link.Element))
temp2 = temp2.Link;
else
temp2=temp2.Link;
temp1=temp1.Link;
}
}
public boolean IsEmpty() {
return FirstNode == null;
}
public int SizeOf() {
return Size;
}
public void InsertArbitrary() {
System.out.print("Where To Put Node : ");
int Location = UserInput.nextInt();
if (Location > Size) {
System.out.println("Invalid Input.Try again");
return;
} else if (Location < 0) {
System.out.println("Invalid Input.Try again");
return;
} else if (Location == 1) {
System.out
.printf("Enter something to save in Node %d : ", Location);
Object Element = UserInfo.nextLine();
FirstNode = new Node(Element, FirstNode);
} else if (Location > 0 && Location <= Size) {
System.out
.printf("Enter something to save in Node %d : ", Location);
Object Element = UserInfo.nextLine();
Node CurrentNode = FirstNode;
for (int i = 1; i <= Location - 2; i++) {
CurrentNode = CurrentNode.Link;
}
Node NewNode = new Node(Element, CurrentNode.Link);
CurrentNode.Link = NewNode;
} else {
System.out.println("Invalid Number . Try again.");
return;
}
Size++;
}
public void ShowOff() {
Node Temp;
Temp = FirstNode;
int number = 1;
while (Temp != null) {
System.out.println(Temp.Element);
Temp = Temp.Link;
number++;
}
}
protected boolean ListIsEmpty() {
return FirstNode == null;
}
}
我复制了我执行其他函数的更多细节。我也追踪了我的程序,但没有发现我的逻辑错误。请帮我解决这个问题。提前感谢。
请注意,链接列表本质上是越野车,即使是有经验的程序员。许多仔细的测试和调试是必需的。 – 2015-04-04 21:45:51