Singly-linked list/Element removal: Difference between revisions

m
syntax highlighting fixup automation
m (→‎{{header|Phix}}: syntax coloured, made p2js compatible)
m (syntax highlighting fixup automation)
Line 14:
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}}
<langsyntaxhighlight Actionlang="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!
Line 125:
TestRemove(p)
TestRemove(listBegin)
RETURN</langsyntaxhighlight>
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Singly-linked_list_element_removal.png Screenshot from Atari 8-bit computer]
Line 150:
Using the STRINGLIST from the Singly-linked list Element traversal task.
{{Trans|ALGOL_W}}
<langsyntaxhighlight lang="algol68"># removes the specified element from the list, modifying list if necessary #
PRIO REMOVE = 1;
OP REMOVE = ( REF STRINGLIST list, REF STRINGLIST element )REF STRINGLIST:
Line 189:
( list REMOVE next OF next OF list ) REMOVE list;
 
</syntaxhighlight>
</lang>
 
=={{header|ALGOL W}}==
Uses the ListI record from the Singly Linked List task.
<langsyntaxhighlight lang="algolw">
% deletes the specified element from the list %
% if the element to remove is null or not in the list, %
Line 223:
Remove( head, head );
 
</syntaxhighlight>
</lang>
 
=={{header|ATS}}==
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.
 
<langsyntaxhighlight ATSlang="ats">(*------------------------------------------------------------------*)
 
(* The Rosetta Code linear list type can contain any vt@ype.
Line 373:
 
implement
main0 () = ()</langsyntaxhighlight>
 
{{out}}
Line 386:
=={{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.
<syntaxhighlight lang="c">
<lang C>
#include<stdlib.h>
#include<stdio.h>
Line 486:
return 0;
}
</syntaxhighlight>
</lang>
Invocation, interaction and output :
<pre>
Line 503:
Semantically identical translation of Torvalds' tasteful C version using C# unsafe pointers:
 
<langsyntaxhighlight lang="csharp">using System;
using System.Runtime.InteropServices;
 
Line 554:
Console.WriteLine("after removing second node: " + head->ToString());
}
}</langsyntaxhighlight>
 
{{out}}
Line 563:
 
=={{header|C++}}==
<langsyntaxhighlight lang="cpp">#include <iostream>
 
// define a singly linked list
Line 624:
PrintList(head);
if (!removed2) std::cout << "\nItem not found\n";
}</langsyntaxhighlight>
{{out}}
<pre>
Line 635:
=={{header|F_Sharp|F#}}==
Not really a functional thing to do but...
<langsyntaxhighlight lang="fsharp">
// Singly-linked list/Element removal. Nigel Galloway: March 22nd., 2022
let N=[23;42;1;13;0]
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)
</syntaxhighlight>
</lang>
{{out}}
<pre>
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.
 
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. <langsyntaxhighlight Fortranlang="fortran"> MODULE SIMPLELINKEDLIST !Play with an array. Other arrays might hold content.
CONTAINS !Demonstration only!
SUBROUTINE LLREMOVE(LINK,X) !Remove entry X from the links in LINK.
Line 701:
CALL LLFOLLOW(LINK) !But, I know where it was, in this example.
 
END</langsyntaxhighlight>
Output:
<pre>
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?
 
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 <langsyntaxhighlight Fortranlang="fortran"> IT = 0 !This list element fingers the start of the list..
1 NEXT = LINK(IT) !This is the node of interest.
IF (NEXT.GT.0) THEN !Is it a live node?
Line 744:
GO TO 1 !And try afresh.
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.
 
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 <langsyntaxhighlight Fortranlang="fortran"> IT = 0 !This list element fingers the start of the list..
DO WHILE((NEXT = LINK(IT)).GT.0) !Finger the follower of IT.
IF (NEXT.EQ.X) THEN !Is it the unwanted one?
Line 755:
IT = NEXT !Advance to the follower.
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.
 
=={{header|FreeBASIC}}==
{{trans|Yabasic}}
<langsyntaxhighlight lang="freebasic">#define FIL 1
#define DATO 2
#define LINK 3
Line 827:
Print
printNode(1)
printNode(2)</langsyntaxhighlight>
{{out}}
<pre>1000
Line 838:
=={{header|Go}}==
This reuses code from other singly-linked list tasks.
<langsyntaxhighlight lang="go">package main
 
import "fmt"
Line 924:
fmt.Println("\nAfter removing burritos:")
head.Traverse()
}</langsyntaxhighlight>
 
{{out}}
Line 960:
to take advantage of jq's tail-call optimization (TCO).
 
<langsyntaxhighlight lang="jq"># Input: a JSON object representing a SLL
# Output: an object with the same value after
# removal of the first item for which (.item|f) is truthy
Line 983:
else .
end;
r;</langsyntaxhighlight>
'''Example'''
<langsyntaxhighlight lang="jq">{
"item": 1,
"next": {
Line 992:
}
}
| remove_all(. == 1)</langsyntaxhighlight>
{{out}}
<pre>
Line 1,004:
{{works with|Julia|0.6}}
See the <tt>LinkedList</tt> defined at [[Singly-linked_list/Element_definition#Julia]].
<langsyntaxhighlight lang="julia">function Base.deleteat!(ll::LinkedList, index::Integer)
if isempty(ll) throw(BoundsError()) end
if index == 1
Line 1,020:
end
return ll
end</langsyntaxhighlight>
 
=={{header|Kotlin}}==
<langsyntaxhighlight lang="scala">// version 1.1.2
 
class Node<T: Number>(var data: T, var next: Node<T>? = null) {
Line 1,070:
remove(a, b) // remove last node
println("After 2nd removal : $a")
}</langsyntaxhighlight>
 
{{out}}
Line 1,081:
 
=={{header|Nim}}==
<langsyntaxhighlight Nimlang="nim">import strutils
 
type
Line 1,153:
echo "After removing 1: ", list
list.remove(list.find(5))
echo "After removing 5: ", list</langsyntaxhighlight>
 
{{out}}
Line 1,167:
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.
<!--<langsyntaxhighlight Phixlang="phix">(phixonline)-->
<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>
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;">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>
<!--</langsyntaxhighlight>-->
{{out}}
<pre>
Line 1,275:
=={{header|PicoLisp}}==
===Non destructive===
<langsyntaxhighlight PicoLisplang="picolisp">(de delnon (Item Lst)
(if (index Item Lst)
(conc
Line 1,285:
(println 'L L)
(setq L (delnon N L))
(println 'fin L) )</langsyntaxhighlight>
{{out}}
<pre>
Line 1,292:
</pre>
===Destructive===
<langsyntaxhighlight PicoLisplang="picolisp">(de deldestr (Item "Var")
(let Lst (val "Var")
(let? M (member Item Lst)
Line 1,302:
(println 'L L)
(deldestr N 'L)
(println 'fin 'L L) )</langsyntaxhighlight>
{{out}}
<pre>
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.
 
<langsyntaxhighlight lang="python">
class Node:
def __init__(self, data=None):
Line 1,376:
mylist.print_llist()
 
</syntaxhighlight>
</lang>
 
{{out}}
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)
 
<langsyntaxhighlight lang="racket">#lang racket/base
 
(define (rev l (acc null))
Line 1,421:
(displayln (remove-at '(1 2 3) 1))
(displayln (remove-at '(1 2 3) 2))
(displayln (remove-at '(1 2 3) 3))</langsyntaxhighlight>
 
{{out}}
Line 1,434:
Extending <tt>class Cell</tt> from [[Singly-linked_list/Element_definition#Raku]]:
 
<syntaxhighlight lang="raku" perl6line> method delete ($value --> Cell) {
my $prev = Nil;
my $cell = self;
Line 1,453:
return $new-head;
}</langsyntaxhighlight>
 
Usage:
 
<syntaxhighlight lang="raku" perl6line>my $list = cons 10, (cons 20, (cons 10, (cons 30, Nil)));
 
$list = $list.delete(10);</langsyntaxhighlight>
 
=={{header|Visual Basic .NET}}==
Line 1,473:
- The entry has been removed.
 
<langsyntaxhighlight lang="vbnet">
 
Module Module1
Line 1,529:
End Module
 
</syntaxhighlight>
</lang>
 
=={{header|Wren}}==
{{libheader|Wren-llist}}
<langsyntaxhighlight lang="ecmascript">import "/llist" for LinkedList
 
var ll = LinkedList.new(["dog", "cat", "bear"])
Line 1,540:
System.print("After removal 1: %(ll)")
ll.removeAt(0) // remove by index
System.print("After removal 2: %(ll)")</langsyntaxhighlight>
 
{{out}}
Line 1,550:
 
=={{header|Yabasic}}==
<langsyntaxhighlight Yabasiclang="yabasic">// Rosetta Code problem: http://rosettacode.org/wiki/Singly-linked_list/Element_insertion & removal
// by Galileo, 02/2022
 
Line 1,624:
print
printNode(1)
printNode(2)</langsyntaxhighlight>
{{out}}
<pre>1000
10,327

edits