How do i delete the first instance of a linked list?

2 visualizaciones (últimos 30 días)
Bjartur Kjærbo
Bjartur Kjærbo el 20 de Mayo de 2020
Respondida: Omega el 20 de Sept. de 2024
I have managed to delete every other elemnt but the first with the following code:
properties
% Sets the properties of the obj for the class, also called Node in
% this case. next is to connect the next node and prev is to
% connect current node to the previous
data
next = Elem.empty
prev = Elem.empty
end
function delete(node, a)
b = node.data;
while b ~= a
node = node.next;
b = node.next.data;
if isempty(node.next)
disp('Elemnt is not in the list!')
return
end
end
node.next = node.next.next;
end
When then trying to delete the first element or node, it deletes the next, which i understand.
i have tried making it a double linked list but with no luck, i dont see the right way of connecting the node to the previous.

Respuestas (1)

Omega
Omega el 20 de Sept. de 2024
Hi Bjartur,
I understand that you are facing difficulties with deleting the first node of a doubluy linked list.
To delete the first node in a doubly linked list, you need to adjust the pointers. If the first node is being deleted, copy the data from the next node to the current one and update the links. Make sure the "prev" pointer of the new first node points correctly. You can refer to the code mentioned below:
function deleteFirst(node)
if isempty(node.next)
disp('Cannot delete the only element in the list!');
return;
end
% Update the head to point to the next node
node.data = node.next.data;
node.next = node.next.next;
% Update the previous pointer of the new first node
if ~isempty(node.next)
node.next.prev = node;
end
end

Categorías

Más información sobre Software Development Tools en Help Center y File Exchange.

Etiquetas

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by