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!