How do i delete the first instance of a linked list?
2 次查看(过去 30 天)
显示 更早的评论
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.
0 个评论
回答(1 个)
Omega
2024-9-20
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
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Software Development Tools 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!