Just looking for some advice on my code, im trying to add a Node after a Node contains a specific value. So far i have got it to insert the Node but it seems to skip one Node then insert. So its always inserting one Node too far. Heres the code i came up with...
public void addAfterData(int obj)
{
int dataStop=7;
ListNode newNode = new ListNode();
ListNode insert = new ListNode(obj);
newNode = head;
while(newNode != null && newNode.data != dataStop)
{
newNode = newNode.link;
if(newNode != null)
{
insert.link = newNode.link;
newNode.link = insert;
}
}
}
1 Answer 1
The normal code to add a new after a node which contains a specific value would be this:
public void addNodeAfterData(Node head, Node node, int data)
{
while (head != null && head.data != data)
{
head = head.next;
}
if (head != null)
{
node.next = head.next;
head.next = node;
}
}
basically what we do here is move the head
pointer to the location of the data we're looking, then, when we exit the while loop, we either reached the end because we didnt find the value, so we wont add it (or add it to the end, up to how you define that behavior), or if its not null, so we did find it, and then we make the node we're adding to point to the rest of the list, and we make the current node containing data
to our node.
-
Thanks, i think im getting to grips with the linked lists more now, im totally new to the language its taking a while for everything to sink in. Am i right in thinking that when we do find the specified point in the while loop and we exit, the if statement connect the rest of the list with the given 2 lines we put in. I thought the if statement would need to stay in the while loop as if we did find the point it would break the cycle of adding the newNode to the list.user4556046– user45560462015年02月12日 21:40:56 +00:00Commented Feb 12, 2015 at 21:40
-
@DeanDuff You can do everything in many ways. and yes, the while loop is responsible for moving to the right location, and the if to do the actual insertion. in this case, if you'd like to move the if statement into the while loop, well, thats possible, but you'll have to change the condition to something more appropriate, because head will almost always not be null. you could use
if (head != null && head.data == data)
, but it makes things look a bit more complicated. separating things to easier conditions is always better.buddy123– buddy1232015年02月13日 07:32:10 +00:00Commented Feb 13, 2015 at 7:32
dataStop
being used for?