Data Structures and Algo

Hello everyone!
How can I add a node before in a given node in Singly Linked list.
Thank you!

I am using java, and I have created the a snippet on how to add After a node like this

public voided addAfter(int target value, int data)  {

Node tmp;
for (tmp=head; tmp.data!=target value && tmp.next!=null; tmp = tmp.next) {
}
Node nextOfTmp = tmp.next;
tmp.next = new Node(data, nextOfTmp);
}

That is what I have coded for addAfter and now I am troubled if how Am I supposed to add Before a given node

Do you understand the concept of a linked list? If so it should be pretty easy to visualize the algorithm for doing this. As to how to code this, that would depend on the language and how you are implementing the list. You would need to give us more specifics. Preferably, give us the code that you have so far so we can see what you have tried and then help you get the result you want.

I am using java, and I have created the a snippet on how to addAfter a node like this

public voided addAfter(int target value, int data)  {

Node tmp;
for (tmp=head; tmp.data!=target value && tmp.next!=null; tmp = tmp.next) {
}
Node nextOfTmp = tmp.next;
tmp.next = new Node(data, nextOfTmp);
}

That is what I have coded for addAfter and now I am troubled if how Am I supposed to add Before a given node

I am using java, and I have created the a snippet on how to addAfter a node like this

public voided addAfter(int target value, int data)  {

Node tmp;
for (tmp=head; tmp.data!=target value && tmp.next!=null; tmp = tmp.next) {
}
Node nextOfTmp = tmp.next;
tmp.next = new Node(data, nextOfTmp);
}

That is what I have coded for addAfter and now I am troubled if how Am I supposed to add Before a given node

I’ve edited your post for readability. When you enter a code block into a forum post, please precede it with a separate line of three backticks and follow it with a separate line of three backticks to make it easier to read.

You can also use the “preformatted text” tool in the editor (</>) to add backticks around text.

See this post to find the backtick on your keyboard.
Note: Backticks (`) are not single quotes (’).

Because you cannot go backwards in a single-LL, you have to keep track of the currentNode and the previousNode. Once the currentNode has your target value, you insert the newNode inbetween.

Thank you! very much for your help!

Thank you very much! for your help