Pop operation in linked list

Write a Pop() function that is the inverse of Push(). Pop() takes a non-empty list, deletes the head node, and returns the head node’s data.

 


 

Pop() operation is a bit tricky as it needs to unlink the front node from the list and deallocate it with a call to free(). Pop() needs to use a reference parameter like Push() so that it can change the caller’s head pointer. So we extract the data from the head node, delete the node, advance the head pointer to point at the next node in line. Below code uses a reference parameter since it changes the head pointer.

 
C++ implementation –
 

Download   Run Code

Output:

Popped node 1
2 -> 3 -> 4 -> null

 

 
Source:
http://cslibrary.stanford.edu/105/LinkedListProblems.pdf

 
Thanks for reading.




Please use ideone or C++ Shell or any other online compiler link to post code in comments.
Like us? Please spread the word and help us grow. Happy coding 🙂