如何访问链接列表的元素?

时间:2011-03-05 11:47:11

标签: java linked-list

由于Java中没有自引用指针概念......如何解决此问题......

我不允许在Java中使用内置的Link List类...

但是“应该遵循与C中相同的创建链接列表的方法”。什么可能是最好的替代节点 - >接下来,节点 - >在Java中流行...

2 个答案:

答案 0 :(得分:5)

可以通过创建一个具有自身成员变量的类来实现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  }

要创建链接列表,请创建head:

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()
}

答案 1 :(得分:0)

“this”关键字是指向self的指针。 问题的其余部分 - 请澄清。

相关问题