Singly-linked list/Element insertion: Difference between revisions
Singly-linked list/Element insertion (view source)
Revision as of 15:11, 28 August 2022
, 1 year agosyntax highlighting fixup automation
(Add Zig example) |
Thundergnat (talk | contribs) m (syntax highlighting fixup automation) |
||
Line 8:
=={{header|360 Assembly}}==
The program uses one ASSIST macro (XPRNT) to keep the code as short as possible.
<
LISTSINA CSECT
USING LISTSINA,R13 base register
Line 94:
NEXT DS A
YREGS
END LISTSINA</
{{out}}
<pre>
Line 104:
=={{header|AArch64 Assembly}}==
{{works with|as|Raspberry Pi 3B version Buster 64 bits}}
<syntaxhighlight lang="aarch64 assembly">
/* ARM assembly AARCH64 Raspberry PI 3B */
/* program insertList64.s */
Line 229:
/* for this file see task include a file in language AArch64 assembly */
.include "../includeARM64.inc"
</syntaxhighlight>
=={{header|ACL2}}==
<
(cond ((endp xs)
nil)
Line 239:
(cons e (rest xs))))
(t (cons (first xs)
(insert-after x e (rest xs))))))</
Example:
Line 248:
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}}
<
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 338:
TestAddAfter('C,listBegin)
TestClear()
RETURN</
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Singly-linked_list_element_insertion.png Screenshot from Atari 8-bit computer]
Line 355:
=={{header|ActionScript}}==
Insertion method:
<
{
public class Node
Line 368:
}
}
}</
Usage:
<
var A:Node = new Node(1);
Line 376:
var C:Node = new Node(3);
A.insert(B);
A.insert(C);</
=={{header|Ada}}==
We must create a context clause making the predefined generic procedure Ada.Unchecked_Deallocation visible to this program.
<
-- Define the link type
procedure Singly_Linked is
Line 413:
Free(B);
Free(C);
end Singly_Linked;</
=={{header|ALGOL 68}}==
Line 419:
standard library. However Linked lists are presented in standard text
book examples. Or can be manually constructed, eg:
<
STRINGLIST list := ("Big",
Line 443:
node := next OF node
OD;
print((newline))</
Output:<pre>Big fjords vex VERY quick waltz nymph </pre>
=={{header|ALGOL W}}==
<
procedure insert( reference(ListI) value list
; integer value newValue
Line 460:
% insert a new value into the list %
insert( next(head), 4077 );</
=={{header|ARM Assembly}}==
{{works with|as|Raspberry Pi}}
<syntaxhighlight lang="arm assembly">
/* ARM assembly Raspberry PI */
/* program insertList.s */
Line 644:
bx lr @ leave function
iMagicNumber: .int 0xCCCCCCCD
</syntaxhighlight>
=={{header|ATS}}==
Line 658:
that the insertion routine will terminate.
<
(* The Rosetta Code linear list type can contain any vt@ype.
Line 774:
implement
main0 () = ()</
{{out}}
Line 783:
=={{header|AutoHotkey}}==
<syntaxhighlight lang="autohotkey">a = 1
a_next = b
b = 2
Line 799:
%old%_next := new
%new%_next := temp
}</
=={{header|Axe}}==
<
{r₁+2}ʳ→{r₂+2}ʳ
r₂→{r₁+2}ʳ
r₁
Return</
=={{header|BBC BASIC}}==
{{works with|BBC BASIC for Windows}}
<
DIM a{} = node{}, b{} = node{}, c{} = node{}
Line 825:
here.pNext% = new{}
ENDPROC
</syntaxhighlight>
=={{header|C}}==
Line 831:
Define the method:
<
newlink->next = anchor->next;
anchor->next = newlink;
}</
Note that in a production implementation, one should check anchor and newlink to ensure they're valid values. (I.e., not NULL.)
Line 841:
Create our links.
<
a = malloc(sizeof(link));
b = malloc(sizeof(link));
Line 847:
a->data = 1;
b->data = 2;
c->data = 3;</
Prepare our initial list
<syntaxhighlight lang
Insert element c after element a
<syntaxhighlight lang
Remember to free the memory once we're done.
<
free (b);
free (c);</
=={{header|C sharp|C#}}==
Line 864:
Creates nodes and inserts them from the data passed.
<
{
prev.Next = new Link() { Value = value, Next = prev.Next };
}</
<
{
//Create A(5)->B(7)
Line 876:
//Insert C between A and B
InsertAfter(A, 15);
}</
=={{header|C++}}==
This uses the generic version of the link node. Of course, normally this would be just some implementation detail inside some list class, not to be used directly by client code.
<
{
new_node->next = list_node->next;
list_node->next = new_node;
};</
Here's the example code using that method:
The following code creates the links. As numeric values I've just taken the corresponding character values.
<
link<int>* c = new link<int>('C');</
Now insert c after a:
<syntaxhighlight lang
Finally destroy the list:
<
{
link<int>* tmp = a;
a = a->next;
delete tmp;
}</
=={{header|Clojure}}==
<
(cond (empty? ls) ls
(= (first ls) old) (cons old (cons new (rest ls)))
:else (cons (first ls) (insert-after new old (rest ls)))))</
And the test:
<
(a c b)</
=={{header|Common Lisp}}==
Line 919:
For many list manipulations in Common Lisp, there are both destructive and non-destructive versions. <code>insert-after</code> is non-destructive, copying the structure of list up to and including the occurrence of the old-element, and sharing the list structure afterward. <code>ninsert-after</code> may modify the structure of the input list.
<
"Return a list like list, but with new-element appearing after the
first occurence of old-element. If old-element does not appear in
Line 937:
((or (null next) (funcall test old-element (car prev)))
(rplacd prev (cons new-element next))
list))))</
A simpler implementation that traverses the list a bit more can also be written. This takes advantage of the fact that member returns the tail of the list beginning with the first occurrence of an item, and that ldiff copies as much of its list argument as necessary.
<
(let ((tail (rest (member old-element list :test test))))
(nconc (ldiff list tail)
(cons new-element tail))))</
Lastly, here is a recursive version. Case 3 could be optimized by only doing the rplacd operation when the recursive call returns a tail whose first cell is now different compared to that of the previous tail. (I.e. the recursive call has immediately hit case 1 or 2 which allocate new structure.)
<
"Insert item new into list, before existing, or at the end if existing
is not present. The default comparison test function is EQL. This
Line 962:
;; and make that list the new rest.
(t (rplacd list (insert-before (cdr list) new existing :test test))
list)))</
=={{header|D}}==
<
T data;
typeof(this)* next;
Line 985:
// The GC will collect the memory.
}</
=={{header|Delphi}}==
Line 991:
A simple insertion into a one way list. I use a generic pointer for the data that way it can point to any structure, individual variable or whatever. '''NOTE:''' For original versions of Turbo Pascal, substitute the MemAvail Function for the Try Except block as this does not exist in this version of the pascal language. Also, Turbo Pascal doesn't have C++-style comments, therefore those have to be replaced with Pascal style comments, i.e. { ... } or (* ... *).
<
Type
Line 1,048:
CurrentNode.Next := result ;
end;
end;</
=={{header|E}}==
<
new :LinkedList ? (new.next().null())) {
new.setNext(head.next())
Line 1,069:
println(x.value())
x := x.next()
}</
=={{header|EchoLisp}}==
Lists are mutable, and we use the destructive - and dangerous - set-cdr! operator which modifies the 'rest' part of a list or sub-list.
<
(define (insert-after lst target item)
(when (null? lst) (error "cannot insert in" null))
Line 1,085:
(insert-after L 'x 'y)
L → (a c b y)
</syntaxhighlight>
=={{header|Elena}}==
<
{
insertAfter(Link prev, IntNumber i)
Line 1,094:
prev.Next := new Link(i, prev.Next)
}
}</
=={{header|Erlang}}==
Lists are builtin, but Erlang is single assignment. Here we need mutable link to next element. Mutable in Erlang usually means a process, so:
<syntaxhighlight lang="erlang">
-module( singly_linked_list ).
Line 1,150:
loop_foreach( _Fun, nonext ) -> ok;
loop_foreach( Fun, Next ) -> Next ! {foreach, Fun}.
</syntaxhighlight>
{{out}}
<pre>
Line 1,160:
=={{header|Factor}}==
<
[ swap next>> >>next drop ] [ >>next drop ] 2bi ;
Line 1,168:
[ C <linked-list> list-append ] keep
[ B <linked-list> list-append ] keep
.</
Output:
<pre>
Line 1,186:
Extending Node class from [[Singly-Linked_List_(element)]]:
<
class Node
{
Line 1,221:
}
}
</syntaxhighlight>
Output:
Line 1,233:
Using the linked list concept described in the [[Singly-Linked_List_(element)]] topic:
<
create A 0 , char A ,
create B 0 , char B ,
create C 0 , char C ,</
Now insert b after a and c after b, giving a->b->c
<
C B chain</
Here is an abbreviated version of the definition of 'chain' from the other article:
<
=={{header|Fortran}}==
In ISO Fortran 95 or later:
<
type (node), intent(inout) :: nodeBefore
real, intent(in) :: value
Line 1,256:
newNode%next => nodeBefore%next
nodeBefore%next => newNode
end subroutine addAfter</
=={{header|FreeBASIC}}==
Assumes you already have the ll_int data type, defined [[Singly-linked_list/Element_definition#FreeBASIC|here]].
<
ins->nxt = anchor->nxt
anchor->nxt = ins
end sub</
=={{header|Go}}==
<
import "fmt"
Line 1,303:
h.insert("C")
h.printList()
}</
Output:
<pre>
Line 1,312:
=={{header|Groovy}}==
Solution (uses ListNode from [[Singly-Linked List (element)#Groovy]]):
<
private enum Flag { FRONT }
private ListNode head
Line 1,331:
}
String toString() { "${head}" }
}</
Test:
<
list.insert('B')
list.insert('A')
Line 1,340:
list.insert('C', 'A')
println list</
Output:
Line 1,348:
=={{header|Haskell}}==
This kind of list manipulation is [[unidiomatic]] Haskell. But you can try the following:
<
| otherwise = c : insertAfter a b cs
insertAfter _ _ [] = error "Can't insert"</
==Icon and Unicon==
Line 1,358:
==={{header|Icon}}===
<syntaxhighlight lang="icon">
record Node (value, successor)
Line 1,365:
node.successor := newNode
end
</syntaxhighlight>
==={{header|Unicon}}===
<syntaxhighlight lang="unicon">
class Node (value, successor)
Line 1,381:
self.successor := successor
end
</syntaxhighlight>
=={{header|J}}==
<
A=:0 NB. reference into list
B=:1 NB. reference into list
Line 1,395:
localNewNode=: (localOldLinkRef { localListValue), localNewValue
(localListName)=: (localNewLinkRef localOldLinkRef} localListValue), localNewNode
)</
With these definitions:
Line 1,407:
=={{header|Java}}==
Extending [[Singly-Linked_List_(element)#Java]]
<
{
new_node.next = anchor_node.next;
anchor_node.next = new_node;
}</
{{works with|Java|1.5+}}
Java allows the use of generics to allow the data type to be determined at compile time. This will only work on reference types, not primitive types like int or float (wrapper classes like Integer and Float are available).
Line 1,417:
=={{header|JavaScript}}==
Extending [[Singly-Linked_List_(element)#JavaScript]]
<
if (this._value == searchValue) {
nodeToInsert.next(this.next());
Line 1,428:
}
var list = createLinkedListFromArray(['A','B']);
list.insertAfter('A', new LinkedList('C', null));</
=={{header|jq}}==
Line 1,437:
see [[Singly-linked_list/Element_definition#jq]].
<
if $next | (.==null or is_singly_linked_list)
then {$item, $next}
Line 1,447:
def insert($x):
.next |= new($x; .);</
'''An example''':
<syntaxhighlight lang="jq">
new(1) | insert(2)
</syntaxhighlight>
{{out}}
<pre>
Line 1,467:
See the <tt>LinkedList</tt> implemented at [[Singly-linked_list/Element_definition#Julia]].
<
if index == 1
if isempty(ll)
Line 1,487:
end
return ll
end</
=={{header|Kotlin}}==
<
class Node<T: Number>(var data: T, var next: Node<T>? = null) {
Line 1,516:
insertAfter(a, c)
println("After insertion : $a")
}</
{{out}}
Line 1,525:
=={{header|Logo}}==
<
localmake "tail member :after :list
if not empty? :tail [.setbf :tail fput :value bf :tail]
Line 1,531:
end
show insert 5 [3 5 1 8] 2</
[3 5 2 1 8]
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<
->{a, b, c}</
=={{header|Modula-3}}==
<
TYPE
Line 1,564:
InsertAppend(a, b);
InsertAppend(a, c)
END SinglyLinkedList.</
=={{header|Nim}}==
<
next: Node[T]
data: T
Line 1,583:
a.insertAppend(b)
b.insertAppend(c)</
=={{header|OCaml}}==
This kind of list manipulation is unidiomatic OCaml. But you can try the following:
<
c :: cs when a = c -> a :: b :: cs
| c :: cs -> c :: insert_after a b cs
| [] -> raise Not_found</
=={{header|Oforth}}==
Line 1,596:
Method forEachNext is defined in order to traverse the LinkedList. This method is used by println (as a LinkedLIst is defined as a subclass of Collection).
<
LinkedList method: initialize := next := data ;
Line 1,611:
: testLink LinkedList new($A, null) dup add($B) dup add($C) ;
testLink println</
{{out}}
Line 1,620:
=={{header|ooRexx}}==
See [[Singly-linked_list/Element_definition#ooRexx|Single-linked list/Element definition]] for full class definition.
<syntaxhighlight lang="oorexx">
list = .linkedlist~new
index = list~insert("abc") -- insert a first item, keeping the index
Line 1,627:
list~insert("456", index) -- inserts between "abc" and "def"
list~remove(index) -- removes "abc"
</syntaxhighlight>
=={{header|Pascal}}==
Line 1,634:
Since Standard Pascal doesn't know a generic pointer type, and also no generic types, one has to settle for a specific data type for the linked list. Since the task mentions node names "A", "B", "C", here a char is chosen. Of course any data type (including pointers to a specific data type) could have been used here.
<
pCharNode = ^CharNode;
CharNode = record
Line 1,648:
newnode^.next := listnode^.next;
listnode^.next := newnode;
end;</
Usage example:
<
A, B: pCharNode;
begin
Line 1,676:
dispose(B);
end
end.</
=={{header|Perl}}==
If you don't really need the constant-time insertion property of singly linked lists, just use an array. You can traverse and splice it any way.
<
push @l, $C, splice @l, 1;</
However, if you really need a linked list, or all you got is an algorithm in a foreign language, you can use references to accomplish the translation.
<
# first argument: node to insert after
# second argument: node to insert
Line 1,701:
data => 2,
);
insert_after \%A, \%C;</
Note that you don't have to name your new nodes. The following works just as well:
<
Note the curly braces instead of round parentheses.
It is straightforward to extend the function to take an arbitrary number of list nodes to insert:
<
my $node = $_[0];
my $next = $node->{next};
Line 1,717:
}
$node->{next} = $next;
}</
With this, it's rather easy to build a list:
<
insert_after \%list, { data => 'B' }, { data => 'C' };</
List handling is simplified if the variables themselves contain references. For example:
<
# create a new list ('A'. 'B', 'C') and store it in $list2
Line 1,731:
# append new nodes ('A2a', 'A2b') after the second element (which now is 'A2')
insert_after $list2->{next}, { data => 'A2a' }, { data => 'A2b' };</
=={{header|Phix}}==
See also [[Singly-linked_list/Traversal#Phix|Traversal]] and [[Singly-linked_list/Element_removal#Phix|Removal]].
<!--<
<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,751:
<span style="color: #0000FF;">?</span><span style="color: #000000;">sll</span>
<!--</
{{out}}
<pre>
Line 1,759:
=={{header|PicoLisp}}==
Destructive operation
<
(when (member Item Lst)
(con @ (cons New (cdr @))) )
Lst )</
Non-destructive operation
<
(if (index Item Lst)
(conc (cut @ 'Lst) (cons New Lst))
Lst ) )</
Output in both cases:
<pre>: (insertAfter 'A '(A B) 'C)
Line 1,776:
=={{header|PL/I}}==
<syntaxhighlight lang="pl/i">
/* Let H be a pointer to a node in a one-way-linked list. */
/* Insert an element, whose value is given by variable V, following that node. */
Line 1,784:
node.value = V;
H->p = Q; /* Break the list at H, and point it at the new node. */
</syntaxhighlight>
=={{header|Pop11}}==
Line 1,790:
In Pop11 one normally uses built-in lists:
<
cons(x, back(anchor)) -> back(anchor);
enddefine;
Line 1,797:
insert_into_list(l1, "b");
;;; insert c
insert_into_list(l1, "c");</
If one wants one can use user-defined list node (for convenience we repeat definition of list node):
<
define :class ListNode;
slot value = [];
Line 1,814:
insert_into_List(l2, "b");
;;; insert c
insert_into_List(l2, "c");</
Note that user-defined case differs from built-in case only because of names.
=={{header|PureBasic}}==
<
Protected *newNode.MyData = AllocateMemory(SizeOf(MyData))
If *newNode
Line 1,836:
*SL_List = insertAfter(a) ;start the list
insertAfter(b, *SL_List) ;insert after head of list
insertAfter(c, *SL_List) ;insert after head of list and before tail</
=={{header|Python}}==
<
while lst is not None:
if lst[0] == at:
Line 1,850:
chain = ['A', ['B', None]]
chain_insert(chain, 'A', 'C')
print chain</
Output:
<
=={{header|Racket}}==
<syntaxhighlight lang="racket">
#lang racket
Line 1,868:
(insert-after! l 2 2.5)
l ; -> (mcons 1 (mcons 2 (mcons 2.5 (mcons 3))))
</syntaxhighlight>
=={{header|Raku}}==
Line 1,875:
Extending <tt>class Cell</tt> from [[Singly-linked_list/Element_definition#Raku]]:
<syntaxhighlight lang="raku"
$.next = Cell.new(:$value, :$.next)
}</
=={{header|REXX}}==
<
@.=0 /*define a null linked list. */
call set@ 3 /*linked list: 12 Proth primes. */
Line 1,933:
@..y=n /*set a locator pointer to self. */
@.max_width=max(@.max_width,length(y)) /*set maximum width of any value.*/
return /*return to invoker of this sub. */</
'''output'''
<pre>
Line 1,971:
=={{header|Ruby}}==
<
def insert_after(search_value, new_value)
if search_value == value
Line 1,984:
list = ListNode.new(:a, ListNode.new(:b))
list.insert_after(:a, :c)</
=={{header|Rust}}==
Extending [[Singly-Linked List (element)#Rust]]. Please see that page for the Linked List struct declarations.
<
pub fn new() -> Self {
List { head: None }
Line 2,000:
});
self.head = Some(new_node);
}</
=={{header|Scala}}==
In Scala (and functional programming) we create a new list instead of modifying existing one.
<
/*
Here is a basic list definition
Line 2,016:
def add[A](as: List[A], a: A): List[A] = Cons(a, as)
}
</syntaxhighlight>
=={{header|Scheme}}==
Non-mutating:
<
(if (null? lst)
lst ; This should be an error, but we will just return the list untouched
Line 2,027:
(if (equal? a c)
(cons a (cons b cs))
(cons c (insert-after a b cs))))))</
Mutating:
<
(let ((pos (member a lst)))
(if pos
(set-cdr! pos (cons b (cdr pos))))))</
=={{header|Sidef}}==
<
b{:next} = a{:next};
a{:next} = b;
Line 2,053:
);
insert_after(A, C);</
=={{header|Stata}}==
Line 2,067:
No error checking is included.
<
proc insertIntoList {existingList predecessor newElement} {
upvar $existingList exList
Line 2,076:
insertIntoList list A C
puts $list
</syntaxhighlight>
{{out}}
<pre>
Line 2,084:
=={{header|Wren}}==
{{libheader|Wren-llist}}
<
var ll = LinkedList.new(["A", "B"])
ll.insertAfter("A", "C")
System.print(ll)</
{{out}}
Line 2,096:
=={{header|X86 Assembly}}==
<
; x86_64 Linux NASM
; Linked_List_Insert.asm
Line 2,126:
%endif
</syntaxhighlight>
=={{header|XPL0}}==
<
def IntSize = 4; \number of bytes in an integer
Line 2,156:
MyNode:= MyNode(Link); \move to next node
];
]</
{{out}}
Line 2,164:
=={{header|Yabasic}}==
<
// by Galileo, 02/2022
Line 2,224:
printNode(1)
printNode(2)
printNode(3)</
<pre>1000
3000
Line 2,232:
=={{header|zkl}}==
In place:
<
a:=L("a","b","c"); a.insert(a.find("b"),"foo") //-->L("a","foo","b","c")</
Create a new list:
<
n:=a.index("b"); a[0,n].append("foo").extend(a[n,*]) //-->ROList("a","foo","b","c")</
=={{header|Zig}}==
<
const std = @import("std");
Line 2,282:
};
}
</syntaxhighlight>
Create a new list:
<
var l1 = LinkedList(i32).init();
</syntaxhighlight>
Add element:
<
try list.add(1);
</syntaxhighlight>
|