Circular LinkedList implementation in Java

空扰寡人 提交于 2019-11-30 18:25:18

When you add a new Node to your list, you add the new Node into the second position (first.next points to your newly added node), but this newly added node has first as its next node, leaving the rest of the list unreferenced (And thus garbage-collected and destroyed). With your add method as it is, it's impossible for your list to contain anything other than 0, 1 or 2 Nodes. It's a bit odd to add new Node into the middle of the list; either add it to the front (newnode.next = first; first = newnode; last.next = first;), or keep a reference to the back of the list (as others have suggested), and add it there.

Personally, I'd restructure the LastNumberNode class so that it has the following methods for manipulating the linkedlist:

  • private void addNode(Node node)
  • private void removeNode(Node node)
  • private Node findNode(Node nextNode)

If you maintain a reference to the last node in the list then your addNode(Node node) method can be something like the following:

if(isEmpty()) {
    first = node;
    last = node;
}
else {
    Node tail = last;
    tail.next = node;
    node.next = first;
    last = node;
}

removeNode(Node node) is based around the following:

Node prevNode = findNode(node);

if(node == first) {
    first = node.next;
    last.next = first;
}
else if(node == last) {
    prevNode.next = first;
    last = prevNode;
}
else {
    prevNode.next = node.next;
}

If I were to implement of this I'd probably do the reduction of the list down to a single Node using this sort of approach:

public String reduceList() {
    Node curNode = first;
    while(first != last) {
        removeNode(curNode.getNext().getNext());
        curNode = curNode.getNext().getNext();
    }

    return first.getValue();
}

As a final point, I wouldn't bother filling an array with sequential numbers and then walking it to add the elements to your list. I'd just go straight for something like the following:

for(int i = 1; i <= input; i++) {
    linkedlist.add(new Integer(i).toString());
}

Your add method inserts the elements directly after first if first is already set:

first.next = new Node(e, first.next);

This leads to the observed behaviour.

You need to keep track of the last element of the list and add the new element as last.next if you want to append the new element at the end of the list. One way to do this is to simply save a reference to the last element in a member variable of the list class, another would be to traverse the list until you find the node linking to first which would be the last node.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!