Thursday, August 19, 2010

How do I delete the last node of a linked list in C programming language?

Also, how do I print a linked list in reverse order?

How do I delete the last node of a linked list in C programming language?
Starting from the first node or head node, go through the list until you get to the last node. You will know its the last node, as it will be pointing to null, or the first node, or the head node, depending on how its set up.


Whilst looping to get to the last node, you will have to keep a record of the node before the last (the node before the one you are testing).


Then all you have to do is change the reference / pointer of this second last node to what the last node pointer to, and delete the last node.





To print in reverse will require recursion, as you want to print the last first, and the first last.


You will once again need to loop until you get to the last node.


For every loop that is not the last node, recall this function with the next node.


Once the last node is found, do not call the function again, but instead print out the value of this node.


Then allow the function to end / return.


As this function now prints out the value of the node, allow the program to do so after calling the function.





Eg,


void function(node)


if node is not last


function(next node) // call the function again with the next node


end if


print value


end function
Reply:The first option you have is to implement a doubly linked list, which is a linked list that you can access from either side. This requires a bit more thinking and a bot more code.





If you just want to use the linked list you have, then use recursion.


recurse through the nodes until you reach a null pointer


when you have a null pointer, you know u are at the last node, so return with a different return value. The previous node will see this value, what it needs to do is release the memory from the other node, and then turn its pointer to null, to mark itself as the last node.





Sry I can't have precise C code, it's been a while since i used it.


No comments:

Post a Comment