开发者

Adding a Node in a doubly-linked list [closed]

开发者 https://www.devze.com 2022-12-24 19:25 出处:网络
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical andcannot be reasonably answered in its current form. For help clari
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center. Closed 9 years ago.

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 );
}
0

精彩评论

暂无评论...
验证码 换一张
取 消