0
Psychonaut

Java help, linked lists/nodes

Recommended Posts

Can anyone help me out?

You can see in LinkList.java I need to build the insertAfter and insertBefore.

What my mind see's, for insertAfter to begin with, is something like this..

public void insertAfter(long dd)  {   

long reference = current.dData;
if (previous == null) {
current = current.next; //Move current over one to make room for insert
previous = reference; //Insert given number
} else {
previous = reference; //Insert given number
}

}

Stay high pull low

Share this post


Link to post
Share on other sites
Disclaimer: I don't write Java for a living and I'm tired. So if you fail your class because you decided to outsource your homework to a discussion forum then its your fault and yours alone.



public void insertAfter(long dd) {
// insert a new node after current node;
Node newNode = new Node(dd);
// if current is not null, don't change it;
if(current != null){
newNode.next = current.next;
current.next = newNode;
}
//otherwise set current to new node.
else{
newNode.next = null;
current = newNode;
previous.next = current;
}
}

public void insertBefore(long dd) {
// insert a new node before current node, always set current to the new node
Node newNode = new Node(dd);
newNode.next = current;
if(previous == null){
current = newNode;
first = current;
}
else{
current = newNode;
previous.next = current;
}


Your rights end where my feelings begin.

Share this post


Link to post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

0