Reputation: 9
So I created my own version of a linked list in C# and one of the methods I'm using is removing the last element from the list. After some fooling around trying to get this to work, I realized that for some reason my code does some funny stuff when trying to remove the last element.
Here is my code for the linked list:
class Node
{
public Node next;
public int data;
}
class LinkedL
{
private Node head;
//Methods...
}
After creating a linked list consisting of 10, 1223, 53, 93, 2830, and 93, I wrote a function within my LinkedL class called Popback that removes the last element of the linked list, in this case 93.
In the following PopBack code, I purposely added a line to reset the temp.next.next to be null before the while loop and it does what I would want it to do had the list head been 10, 1223, and 53, returning 10, 1223. The while loop doesn't seem to do anything though.
public void PopBack()
{
if (head == null) { return; }
Node temp = head;
temp.next.next = null; //this is the added line
while (temp.next != null)
{
temp = temp.next;
}
temp = null;
}
However, if I were to remove that line, it goes through the while loop but even after setting the updated temp to be null, the list (head) doesn't change. I have a similar function to this where I add an element to the end of the linked list and that works just fine. What could be the cause of this?
Upvotes: 0
Views: 66
Reputation: 125640
Setting temp
to null does just that - sets temp
variable to point at null
. It does not change what the Next
property of the previous element points at.
To do what you want and remove the last element you need to modify the second-to-last Node
s Next
to point at null
:
public void PopBack()
{
if (head == null) { return; }
if (head.Next == null) { head = null; return; }
Node temp = head;
while (temp.next.next != null)
{
temp = temp.next;
}
temp.next = null;
}
Update
In one of your comments you mentioned:
Had I used temp = null instead, it would've made head = null like I want it to. Using it after the while loop however, it doesn't seem to affect head at all.
That's not true.
public void PopBack()
{
if (head == null) { return; }
Node temp = head;
temp = null;
// over here head won't be null!
}
You're making both head
and temp
point at the same class instance and later on change temp
to point at null
. head
still points at the same class instance it pointed at before.
Now, if instead of doing temp = null
you do temp.next = null
it is equivalent to doing head.next = null
directly. That's because both temp
and head
point at the same object and you're setting a field on that object to null
.
Upvotes: 2