如何访问链接列表的元素?
问题描述:
由于在Java中没有自我闯民宅指针的概念...我如何着手解决这个问题...如何访问链接列表的元素?
我不能使用内置类链接列表中的Java ...
但是“应该像C中一样遵循创建链接列表的相同方法。”什么可能是Java中最好的替代节点 - >下一个,node-> prev ...
答
而不是一个指向下一个节点和var的对象,在java链接列表中可以通过使用自己的成员变量创建一个类来实现。
样本实现列举如下:
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 }
要创建一个链接列表,创建头:
Node head = new Node(1);
这个节点类有将节点添加到列表中的方法有两种:
Node secondNode = new Node(head, 2);
或
head.addNode(new Node(2))
这里是值1的列表的例子 - 10
Node head = new Node(1);
Node tempPtr = head;
while (tempPtr.getMyInt() <= 10)
{
tempPtr.addNode(new Node(tempPtr.getMyInt()+1));
tempPtr = tempPtr.nextNode();
}
现在你可以打印通过列表迭代访问此列表中的元素。
tempPtr = head;
while (tempPtr != Null)
{
tempPtr.printNode()
tempPtr = tempPtr.nextNode()
}
+0
谢谢..对于快速回复... – 2011-03-05 11:59:15
答
“this”关键字是指向自我的指针。 重新提出您的问题的其余部分 - 请澄清。
你能更具体地回答你的问题吗? – 2011-03-05 11:49:32
Java中默认存在LinkedList。 ArrayList对于大多数列表需求已足够 – 2011-03-05 11:50:54
我不允许在Java中使用链接列表类中的内置...但是“应该遵循与C中一样创建链接列表的方法”。什么可能是最好的替代品node-> next,node-> prev in Java ... – 2011-03-05 11:53:29