由于Java中没有自引用指针概念......如何解决此问题...
我不允许在Java中使用内置类链接列表...
但是"应该像在C中一样遵循链接列表的创建方法".什么可能是最好的替代节点 - >接下来,节点 - > Java中的prev ...
可以通过创建一个具有自身成员变量的类来实现java链接列表中的指向下一个节点和var的指针的对象.
下面列出了一个示例实现:
1 public class Node
2 {
3 private int myInt;
4 private Node nextNode;
5
6 public Node(int val)
7 {
8 myInt = val;
9 nextNode = null;
10 return this;
11 }
12
13 public int getMyInt()
14 {
19 return myInt;
20 }
21
22 public Node(Node prev, int val)
23 {
24 prev.nextNode = this;
25 myInt = val;
26 nextNode = null;
27 }
28
29 public void addNode(Node newNode)
30 {
31 nextNode = newNode;
32 }
33
34 public void printNodes()
35 {
36 System.out.println(myInt);
37 if (nextNode != null)
38 {
39 nextNode.printNodes();
40 }
41 }
42
43 public void printNode()
44 {
45 System.out.println(myInt);
46 }
47
48 public Node nextNode()
49 {
50 return this.nextNode;
51 }
52 }
Run Code Online (Sandbox Code Playgroud)
要创建链接列表,请创建头部:
Node head = new Node(1);
Run Code Online (Sandbox Code Playgroud)
此节点类有两种向列表添加节点的方法:
Node secondNode = new Node(head, 2);
Run Code Online (Sandbox Code Playgroud)
要么
head.addNode(new Node(2))
Run Code Online (Sandbox Code Playgroud)
这是一个值为1 - 10的列表示例
Node head = new Node(1);
Node tempPtr = head;
while ( tempPtr.getMyInt() <= 10 )
{
tempPtr.addNode(new Node(tempPtr.getMyInt()+1));
tempPtr = tempPtr.nextNode();
}
Run Code Online (Sandbox Code Playgroud)
现在,您可以通过遍历列表来打印访问此列表的元素.
tempPtr = head;
while ( tempPtr != Null )
{
tempPtr.printNode()
tempPtr = tempPtr.nextNode()
}
Run Code Online (Sandbox Code Playgroud)