Adding a Node in a doubly-linked list [closed]
I am working on some code were I need to add a Node into a doubly-linked list. This is the code I have so far:
Node tempNext = cursor开发者_StackOverflow社区.getNext();
temp = new Node(item, null, cursor, tempNext);
tempNext.setPrev(temp);
Where cursor
is the Node that is right before where the new added Node should go.
How do I set the other nodes to correctly maintain the state of the doubly-linked list?
Writing meaningful variable names will always help you, never use names like temp*:
protected void insertNodeAfter(Node currentNode, Node newNode) {
Node displacedNode = currentNode.getNext();
currentNode.setNext(newNode);
newNode.setNext(displacedNode)
displacedNode.setPrev(newNode);
newNode.setPrev(currentNode);
}
Seems like all you need to add is
cursor.setNext(temp);
Do you have a specific question?
public void addItemBefore( int info )
{
previousItem = new ListItem( previousItem, info, this );
}
精彩评论