Singly-linked list/Element removal: Difference between revisions

Content added Content deleted
m (→‎{{header|Phix}}: syntax coloured, made p2js compatible)
m (syntax highlighting fixup automation)
Line 14: Line 14:
The user must type in the monitor the following command after compilation and before running the program!<pre>SET EndProg=*</pre>
The user must type in the monitor the following command after compilation and before running the program!<pre>SET EndProg=*</pre>
{{libheader|Action! Tool Kit}}
{{libheader|Action! Tool Kit}}
<lang Action!>CARD EndProg ;required for ALLOCATE.ACT
<syntaxhighlight lang="action!">CARD EndProg ;required for ALLOCATE.ACT


INCLUDE "D2:ALLOCATE.ACT" ;from the Action! Tool Kit. You must type 'SET EndProg=*' from the monitor after compiling, but before running this program!
INCLUDE "D2:ALLOCATE.ACT" ;from the Action! Tool Kit. You must type 'SET EndProg=*' from the monitor after compiling, but before running this program!
Line 125: Line 125:
TestRemove(p)
TestRemove(p)
TestRemove(listBegin)
TestRemove(listBegin)
RETURN</lang>
RETURN</syntaxhighlight>
{{out}}
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Singly-linked_list_element_removal.png Screenshot from Atari 8-bit computer]
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Singly-linked_list_element_removal.png Screenshot from Atari 8-bit computer]
Line 150: Line 150:
Using the STRINGLIST from the Singly-linked list Element traversal task.
Using the STRINGLIST from the Singly-linked list Element traversal task.
{{Trans|ALGOL_W}}
{{Trans|ALGOL_W}}
<lang algol68># removes the specified element from the list, modifying list if necessary #
<syntaxhighlight lang="algol68"># removes the specified element from the list, modifying list if necessary #
PRIO REMOVE = 1;
PRIO REMOVE = 1;
OP REMOVE = ( REF STRINGLIST list, REF STRINGLIST element )REF STRINGLIST:
OP REMOVE = ( REF STRINGLIST list, REF STRINGLIST element )REF STRINGLIST:
Line 189: Line 189:
( list REMOVE next OF next OF list ) REMOVE list;
( list REMOVE next OF next OF list ) REMOVE list;


</syntaxhighlight>
</lang>


=={{header|ALGOL W}}==
=={{header|ALGOL W}}==
Uses the ListI record from the Singly Linked List task.
Uses the ListI record from the Singly Linked List task.
<lang algolw>
<syntaxhighlight lang="algolw">
% deletes the specified element from the list %
% deletes the specified element from the list %
% if the element to remove is null or not in the list, %
% if the element to remove is null or not in the list, %
Line 223: Line 223:
Remove( head, head );
Remove( head, head );


</syntaxhighlight>
</lang>


=={{header|ATS}}==
=={{header|ATS}}==
Line 236: Line 236:
The deletion routine presented here proves that the result is the same length or one node shorter than the original. Also the search is proven to terminate.
The deletion routine presented here proves that the result is the same length or one node shorter than the original. Also the search is proven to terminate.


<lang ATS>(*------------------------------------------------------------------*)
<syntaxhighlight lang="ats">(*------------------------------------------------------------------*)


(* The Rosetta Code linear list type can contain any vt@ype.
(* The Rosetta Code linear list type can contain any vt@ype.
Line 373: Line 373:


implement
implement
main0 () = ()</lang>
main0 () = ()</syntaxhighlight>


{{out}}
{{out}}
Line 386: Line 386:
=={{header|C}}==
=={{header|C}}==
This implementation takes up integers from the command line and then asks which element has to be removed. List is printed before and after removal, usage printed on incorrect invocation.
This implementation takes up integers from the command line and then asks which element has to be removed. List is printed before and after removal, usage printed on incorrect invocation.
<syntaxhighlight lang="c">
<lang C>
#include<stdlib.h>
#include<stdlib.h>
#include<stdio.h>
#include<stdio.h>
Line 486: Line 486:
return 0;
return 0;
}
}
</syntaxhighlight>
</lang>
Invocation, interaction and output :
Invocation, interaction and output :
<pre>
<pre>
Line 503: Line 503:
Semantically identical translation of Torvalds' tasteful C version using C# unsafe pointers:
Semantically identical translation of Torvalds' tasteful C version using C# unsafe pointers:


<lang csharp>using System;
<syntaxhighlight lang="csharp">using System;
using System.Runtime.InteropServices;
using System.Runtime.InteropServices;


Line 554: Line 554:
Console.WriteLine("after removing second node: " + head->ToString());
Console.WriteLine("after removing second node: " + head->ToString());
}
}
}</lang>
}</syntaxhighlight>


{{out}}
{{out}}
Line 563: Line 563:


=={{header|C++}}==
=={{header|C++}}==
<lang cpp>#include <iostream>
<syntaxhighlight lang="cpp">#include <iostream>


// define a singly linked list
// define a singly linked list
Line 624: Line 624:
PrintList(head);
PrintList(head);
if (!removed2) std::cout << "\nItem not found\n";
if (!removed2) std::cout << "\nItem not found\n";
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 635: Line 635:
=={{header|F_Sharp|F#}}==
=={{header|F_Sharp|F#}}==
Not really a functional thing to do but...
Not really a functional thing to do but...
<lang fsharp>
<syntaxhighlight lang="fsharp">
// Singly-linked list/Element removal. Nigel Galloway: March 22nd., 2022
// Singly-linked list/Element removal. Nigel Galloway: March 22nd., 2022
let N=[23;42;1;13;0]
let N=[23;42;1;13;0]
let fG n g=List.indexed n|>List.filter(fun(n,_)->n<>g)|>List.map snd
let fG n g=List.indexed n|>List.filter(fun(n,_)->n<>g)|>List.map snd
printfn " before: %A\nand after: %A" N (fG N 2)
printfn " before: %A\nand after: %A" N (fG N 2)
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 653: Line 653:
For convenience, rather than have the "head" pointer to the first or head element of the linked list be a separate variable, it is found as element zero of the LIST array that holds the links. Because this element is accessible in the same way as the other links in the array representing the linked-list, no special code is needed when it is the head entry that is to be removed and thus it is the pointer to it that must be changed. However, defining arrays starting at index zero is a feature of F90, and having subroutines recognise that their array parameter starts at index zero requires the MODULE protocol. Previously, arrays started with index one, and the code would just have to recognise this with the appropriate offsets, thus, the first element available for an item would be at index two, not one, and so forth. On the other hand, the zero element just needs its link, and any associated cargo would represented wasted storage. If that cargo were to be held in a disc file there would be no such waste, as record numbers start with one, not zero. But, if the linked-list is to be stored entirely in a disc file, the first record has to be reserved to hold the link to the head record and the first available storage record is number two, just as with an array starting at one, not zero. Indeed, a more comprehensive solution would probably reserve the first record as a header, containing a finger to the start of the linked-list, another finger to the start of the "available" (i.e. deleted and thus reusable) linked-list of records, and a record counter to identify the last record in the file so that if the "available" list is empty, the file can be extended by one record to hold a new entry.
For convenience, rather than have the "head" pointer to the first or head element of the linked list be a separate variable, it is found as element zero of the LIST array that holds the links. Because this element is accessible in the same way as the other links in the array representing the linked-list, no special code is needed when it is the head entry that is to be removed and thus it is the pointer to it that must be changed. However, defining arrays starting at index zero is a feature of F90, and having subroutines recognise that their array parameter starts at index zero requires the MODULE protocol. Previously, arrays started with index one, and the code would just have to recognise this with the appropriate offsets, thus, the first element available for an item would be at index two, not one, and so forth. On the other hand, the zero element just needs its link, and any associated cargo would represented wasted storage. If that cargo were to be held in a disc file there would be no such waste, as record numbers start with one, not zero. But, if the linked-list is to be stored entirely in a disc file, the first record has to be reserved to hold the link to the head record and the first available storage record is number two, just as with an array starting at one, not zero. Indeed, a more comprehensive solution would probably reserve the first record as a header, containing a finger to the start of the linked-list, another finger to the start of the "available" (i.e. deleted and thus reusable) linked-list of records, and a record counter to identify the last record in the file so that if the "available" list is empty, the file can be extended by one record to hold a new entry.


Having a value of zero signify that there is no follower is the obvious choice for ending a linked-list. When addresses are being tossed about, this might be dressed up via words such as NULL rather than a literal zero just in case a "null address" does not manifest as a zero value. <lang Fortran> MODULE SIMPLELINKEDLIST !Play with an array. Other arrays might hold content.
Having a value of zero signify that there is no follower is the obvious choice for ending a linked-list. When addresses are being tossed about, this might be dressed up via words such as NULL rather than a literal zero just in case a "null address" does not manifest as a zero value. <syntaxhighlight lang="fortran"> MODULE SIMPLELINKEDLIST !Play with an array. Other arrays might hold content.
CONTAINS !Demonstration only!
CONTAINS !Demonstration only!
SUBROUTINE LLREMOVE(LINK,X) !Remove entry X from the links in LINK.
SUBROUTINE LLREMOVE(LINK,X) !Remove entry X from the links in LINK.
Line 701: Line 701:
CALL LLFOLLOW(LINK) !But, I know where it was, in this example.
CALL LLFOLLOW(LINK) !But, I know where it was, in this example.


END</lang>
END</syntaxhighlight>
Output:
Output:
<pre>
<pre>
Line 734: Line 734:
In messing with linked-lists, one must give close attention to just how an element is identified. Is element X (for removal) the X'th element in sequence along the linked list (first, second, third, etc.), or, is it the element at at a specified memory address or index position X in the LIST array (as here), or, is it the element whose cargo matches X?
In messing with linked-lists, one must give close attention to just how an element is identified. Is element X (for removal) the X'th element in sequence along the linked list (first, second, third, etc.), or, is it the element at at a specified memory address or index position X in the LIST array (as here), or, is it the element whose cargo matches X?


The code involves repeated mention of <code>LINK(IT)</code> and for those who do not have total faith in the brilliance of code generated by a compiler, one could try <lang Fortran> IT = 0 !This list element fingers the start of the list..
The code involves repeated mention of <code>LINK(IT)</code> and for those who do not have total faith in the brilliance of code generated by a compiler, one could try <syntaxhighlight lang="fortran"> IT = 0 !This list element fingers the start of the list..
1 NEXT = LINK(IT) !This is the node of interest.
1 NEXT = LINK(IT) !This is the node of interest.
IF (NEXT.GT.0) THEN !Is it a live node?
IF (NEXT.GT.0) THEN !Is it a live node?
Line 744: Line 744:
GO TO 1 !And try afresh.
GO TO 1 !And try afresh.
END IF !So much for that node.
END IF !So much for that node.
</syntaxhighlight>
</lang>
The introduction of a mnemonic "NEXT" might help the interpretation of the code, but one must be careful about phase: NEXT is the "nextness" for IT which fingers node NEXT which is the candidate for matching against X, not IT. Alternatively, use "FROM" for IT and "IT" for NEXT, being careful to keep it straight.
The introduction of a mnemonic "NEXT" might help the interpretation of the code, but one must be careful about phase: NEXT is the "nextness" for IT which fingers node NEXT which is the candidate for matching against X, not IT. Alternatively, use "FROM" for IT and "IT" for NEXT, being careful to keep it straight.


And ... there is a blatant GO TO (aside from the equivalent concealed via RETURN) but using a WHILE-loop would require a repetition of NEXT = LINK(IT). If Fortran were to enable assignment within an expression (as in Algol) then <lang Fortran> IT = 0 !This list element fingers the start of the list..
And ... there is a blatant GO TO (aside from the equivalent concealed via RETURN) but using a WHILE-loop would require a repetition of NEXT = LINK(IT). If Fortran were to enable assignment within an expression (as in Algol) then <syntaxhighlight lang="fortran"> IT = 0 !This list element fingers the start of the list..
DO WHILE((NEXT = LINK(IT)).GT.0) !Finger the follower of IT.
DO WHILE((NEXT = LINK(IT)).GT.0) !Finger the follower of IT.
IF (NEXT.EQ.X) THEN !Is it the unwanted one?
IF (NEXT.EQ.X) THEN !Is it the unwanted one?
Line 755: Line 755:
IT = NEXT !Advance to the follower.
IT = NEXT !Advance to the follower.
END DO !Ends when node IT's follower is null.
END DO !Ends when node IT's follower is null.
</syntaxhighlight>
</lang>
No label, no nasty literal GO TO - even though an "END DO" hides one.
No label, no nasty literal GO TO - even though an "END DO" hides one.


=={{header|FreeBASIC}}==
=={{header|FreeBASIC}}==
{{trans|Yabasic}}
{{trans|Yabasic}}
<lang freebasic>#define FIL 1
<syntaxhighlight lang="freebasic">#define FIL 1
#define DATO 2
#define DATO 2
#define LINK 3
#define LINK 3
Line 827: Line 827:
Print
Print
printNode(1)
printNode(1)
printNode(2)</lang>
printNode(2)</syntaxhighlight>
{{out}}
{{out}}
<pre>1000
<pre>1000
Line 838: Line 838:
=={{header|Go}}==
=={{header|Go}}==
This reuses code from other singly-linked list tasks.
This reuses code from other singly-linked list tasks.
<lang go>package main
<syntaxhighlight lang="go">package main


import "fmt"
import "fmt"
Line 924: Line 924:
fmt.Println("\nAfter removing burritos:")
fmt.Println("\nAfter removing burritos:")
head.Traverse()
head.Traverse()
}</lang>
}</syntaxhighlight>


{{out}}
{{out}}
Line 960: Line 960:
to take advantage of jq's tail-call optimization (TCO).
to take advantage of jq's tail-call optimization (TCO).


<lang jq># Input: a JSON object representing a SLL
<syntaxhighlight lang="jq"># Input: a JSON object representing a SLL
# Output: an object with the same value after
# Output: an object with the same value after
# removal of the first item for which (.item|f) is truthy
# removal of the first item for which (.item|f) is truthy
Line 983: Line 983:
else .
else .
end;
end;
r;</lang>
r;</syntaxhighlight>
'''Example'''
'''Example'''
<lang jq>{
<syntaxhighlight lang="jq">{
"item": 1,
"item": 1,
"next": {
"next": {
Line 992: Line 992:
}
}
}
}
| remove_all(. == 1)</lang>
| remove_all(. == 1)</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 1,004: Line 1,004:
{{works with|Julia|0.6}}
{{works with|Julia|0.6}}
See the <tt>LinkedList</tt> defined at [[Singly-linked_list/Element_definition#Julia]].
See the <tt>LinkedList</tt> defined at [[Singly-linked_list/Element_definition#Julia]].
<lang julia>function Base.deleteat!(ll::LinkedList, index::Integer)
<syntaxhighlight lang="julia">function Base.deleteat!(ll::LinkedList, index::Integer)
if isempty(ll) throw(BoundsError()) end
if isempty(ll) throw(BoundsError()) end
if index == 1
if index == 1
Line 1,020: Line 1,020:
end
end
return ll
return ll
end</lang>
end</syntaxhighlight>


=={{header|Kotlin}}==
=={{header|Kotlin}}==
<lang scala>// version 1.1.2
<syntaxhighlight lang="scala">// version 1.1.2


class Node<T: Number>(var data: T, var next: Node<T>? = null) {
class Node<T: Number>(var data: T, var next: Node<T>? = null) {
Line 1,070: Line 1,070:
remove(a, b) // remove last node
remove(a, b) // remove last node
println("After 2nd removal : $a")
println("After 2nd removal : $a")
}</lang>
}</syntaxhighlight>


{{out}}
{{out}}
Line 1,081: Line 1,081:


=={{header|Nim}}==
=={{header|Nim}}==
<lang Nim>import strutils
<syntaxhighlight lang="nim">import strutils


type
type
Line 1,153: Line 1,153:
echo "After removing 1: ", list
echo "After removing 1: ", list
list.remove(list.find(5))
list.remove(list.find(5))
echo "After removing 5: ", list</lang>
echo "After removing 5: ", list</syntaxhighlight>


{{out}}
{{out}}
Line 1,167: Line 1,167:
and then mix them up again and remove items in a random order. Obviously remove_item() forms the meat
and then mix them up again and remove items in a random order. Obviously remove_item() forms the meat
of the task requirement; insert_inorder(), show(), and test() aren't really and can be skipped.
of the task requirement; insert_inorder(), show(), and test() aren't really and can be skipped.
<!--<lang Phix>(phixonline)-->
<!--<syntaxhighlight lang="phix">(phixonline)-->
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<span style="color: #008080;">enum</span> <span style="color: #000000;">NEXT</span><span style="color: #0000FF;">,</span><span style="color: #000000;">DATA</span>
<span style="color: #008080;">enum</span> <span style="color: #000000;">NEXT</span><span style="color: #0000FF;">,</span><span style="color: #000000;">DATA</span>
Line 1,258: Line 1,258:
<span style="color: #000000;">test</span><span style="color: #0000FF;">(</span><span style="color: #000000;">ADD</span><span style="color: #0000FF;">,</span><span style="color: #7060A8;">shuffle</span><span style="color: #0000FF;">(</span><span style="color: #000000;">list</span><span style="color: #0000FF;">))</span>
<span style="color: #000000;">test</span><span style="color: #0000FF;">(</span><span style="color: #000000;">ADD</span><span style="color: #0000FF;">,</span><span style="color: #7060A8;">shuffle</span><span style="color: #0000FF;">(</span><span style="color: #000000;">list</span><span style="color: #0000FF;">))</span>
<span style="color: #000000;">test</span><span style="color: #0000FF;">(</span><span style="color: #000000;">REMOVE</span><span style="color: #0000FF;">,</span><span style="color: #7060A8;">shuffle</span><span style="color: #0000FF;">(</span><span style="color: #000000;">list</span><span style="color: #0000FF;">))</span>
<span style="color: #000000;">test</span><span style="color: #0000FF;">(</span><span style="color: #000000;">REMOVE</span><span style="color: #0000FF;">,</span><span style="color: #7060A8;">shuffle</span><span style="color: #0000FF;">(</span><span style="color: #000000;">list</span><span style="color: #0000FF;">))</span>
<!--</lang>-->
<!--</syntaxhighlight>-->
{{out}}
{{out}}
<pre>
<pre>
Line 1,275: Line 1,275:
=={{header|PicoLisp}}==
=={{header|PicoLisp}}==
===Non destructive===
===Non destructive===
<lang PicoLisp>(de delnon (Item Lst)
<syntaxhighlight lang="picolisp">(de delnon (Item Lst)
(if (index Item Lst)
(if (index Item Lst)
(conc
(conc
Line 1,285: Line 1,285:
(println 'L L)
(println 'L L)
(setq L (delnon N L))
(setq L (delnon N L))
(println 'fin L) )</lang>
(println 'fin L) )</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 1,292: Line 1,292:
</pre>
</pre>
===Destructive===
===Destructive===
<lang PicoLisp>(de deldestr (Item "Var")
<syntaxhighlight lang="picolisp">(de deldestr (Item "Var")
(let Lst (val "Var")
(let Lst (val "Var")
(let? M (member Item Lst)
(let? M (member Item Lst)
Line 1,302: Line 1,302:
(println 'L L)
(println 'L L)
(deldestr N 'L)
(deldestr N 'L)
(println 'fin 'L L) )</lang>
(println 'fin 'L L) )</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 1,312: Line 1,312:
I added a lot of comments to be more beginnner friendly. This program will remove elements in any position based on their value, not key.
I added a lot of comments to be more beginnner friendly. This program will remove elements in any position based on their value, not key.


<lang python>
<syntaxhighlight lang="python">
class Node:
class Node:
def __init__(self, data=None):
def __init__(self, data=None):
Line 1,376: Line 1,376:
mylist.print_llist()
mylist.print_llist()


</syntaxhighlight>
</lang>


{{out}}
{{out}}
Line 1,397: Line 1,397:
This is written entirely in terms of car and cdr (the linked list/pair primitives in Racket and Scheme). Usually, you'd have reverse and append available to you... but, again, it's interesting to see how they are implemented (by me, at least)
This is written entirely in terms of car and cdr (the linked list/pair primitives in Racket and Scheme). Usually, you'd have reverse and append available to you... but, again, it's interesting to see how they are implemented (by me, at least)


<lang racket>#lang racket/base
<syntaxhighlight lang="racket">#lang racket/base


(define (rev l (acc null))
(define (rev l (acc null))
Line 1,421: Line 1,421:
(displayln (remove-at '(1 2 3) 1))
(displayln (remove-at '(1 2 3) 1))
(displayln (remove-at '(1 2 3) 2))
(displayln (remove-at '(1 2 3) 2))
(displayln (remove-at '(1 2 3) 3))</lang>
(displayln (remove-at '(1 2 3) 3))</syntaxhighlight>


{{out}}
{{out}}
Line 1,434: Line 1,434:
Extending <tt>class Cell</tt> from [[Singly-linked_list/Element_definition#Raku]]:
Extending <tt>class Cell</tt> from [[Singly-linked_list/Element_definition#Raku]]:


<lang perl6> method delete ($value --> Cell) {
<syntaxhighlight lang="raku" line> method delete ($value --> Cell) {
my $prev = Nil;
my $prev = Nil;
my $cell = self;
my $cell = self;
Line 1,453: Line 1,453:
return $new-head;
return $new-head;
}</lang>
}</syntaxhighlight>


Usage:
Usage:


<lang perl6>my $list = cons 10, (cons 20, (cons 10, (cons 30, Nil)));
<syntaxhighlight lang="raku" line>my $list = cons 10, (cons 20, (cons 10, (cons 30, Nil)));


$list = $list.delete(10);</lang>
$list = $list.delete(10);</syntaxhighlight>


=={{header|Visual Basic .NET}}==
=={{header|Visual Basic .NET}}==
Line 1,473: Line 1,473:
- The entry has been removed.
- The entry has been removed.


<lang vbnet>
<syntaxhighlight lang="vbnet">


Module Module1
Module Module1
Line 1,529: Line 1,529:
End Module
End Module


</syntaxhighlight>
</lang>


=={{header|Wren}}==
=={{header|Wren}}==
{{libheader|Wren-llist}}
{{libheader|Wren-llist}}
<lang ecmascript>import "/llist" for LinkedList
<syntaxhighlight lang="ecmascript">import "/llist" for LinkedList


var ll = LinkedList.new(["dog", "cat", "bear"])
var ll = LinkedList.new(["dog", "cat", "bear"])
Line 1,540: Line 1,540:
System.print("After removal 1: %(ll)")
System.print("After removal 1: %(ll)")
ll.removeAt(0) // remove by index
ll.removeAt(0) // remove by index
System.print("After removal 2: %(ll)")</lang>
System.print("After removal 2: %(ll)")</syntaxhighlight>


{{out}}
{{out}}
Line 1,550: Line 1,550:


=={{header|Yabasic}}==
=={{header|Yabasic}}==
<lang Yabasic>// Rosetta Code problem: http://rosettacode.org/wiki/Singly-linked_list/Element_insertion & removal
<syntaxhighlight lang="yabasic">// Rosetta Code problem: http://rosettacode.org/wiki/Singly-linked_list/Element_insertion & removal
// by Galileo, 02/2022
// by Galileo, 02/2022


Line 1,624: Line 1,624:
print
print
printNode(1)
printNode(1)
printNode(2)</lang>
printNode(2)</syntaxhighlight>
{{out}}
{{out}}
<pre>1000
<pre>1000