Singly-linked list/Element insertion: Difference between revisions

Content added Content deleted
(Add Zig example)
m (syntax highlighting fixup automation)
Line 8: Line 8:
=={{header|360 Assembly}}==
=={{header|360 Assembly}}==
The program uses one ASSIST macro (XPRNT) to keep the code as short as possible.
The program uses one ASSIST macro (XPRNT) to keep the code as short as possible.
<lang 360asm>* Singly-linked list - Insert after 01/02/2017
<syntaxhighlight lang="360asm">* Singly-linked list - Insert after 01/02/2017
LISTSINA CSECT
LISTSINA CSECT
USING LISTSINA,R13 base register
USING LISTSINA,R13 base register
Line 94: Line 94:
NEXT DS A
NEXT DS A
YREGS
YREGS
END LISTSINA</lang>
END LISTSINA</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 104: Line 104:
=={{header|AArch64 Assembly}}==
=={{header|AArch64 Assembly}}==
{{works with|as|Raspberry Pi 3B version Buster 64 bits}}
{{works with|as|Raspberry Pi 3B version Buster 64 bits}}
<syntaxhighlight lang="aarch64 assembly">
<lang AArch64 Assembly>
/* ARM assembly AARCH64 Raspberry PI 3B */
/* ARM assembly AARCH64 Raspberry PI 3B */
/* program insertList64.s */
/* program insertList64.s */
Line 229: Line 229:
/* for this file see task include a file in language AArch64 assembly */
/* for this file see task include a file in language AArch64 assembly */
.include "../includeARM64.inc"
.include "../includeARM64.inc"
</syntaxhighlight>
</lang>


=={{header|ACL2}}==
=={{header|ACL2}}==
<lang Lisp>(defun insert-after (x e xs)
<syntaxhighlight lang="lisp">(defun insert-after (x e xs)
(cond ((endp xs)
(cond ((endp xs)
nil)
nil)
Line 239: Line 239:
(cons e (rest xs))))
(cons e (rest xs))))
(t (cons (first xs)
(t (cons (first xs)
(insert-after x e (rest xs))))))</lang>
(insert-after x e (rest xs))))))</syntaxhighlight>


Example:
Example:
Line 248: Line 248:
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 338: Line 338:
TestAddAfter('C,listBegin)
TestAddAfter('C,listBegin)
TestClear()
TestClear()
RETURN</lang>
RETURN</syntaxhighlight>
{{out}}
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Singly-linked_list_element_insertion.png Screenshot from Atari 8-bit computer]
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Singly-linked_list_element_insertion.png Screenshot from Atari 8-bit computer]
Line 355: Line 355:
=={{header|ActionScript}}==
=={{header|ActionScript}}==
Insertion method:
Insertion method:
<lang ActionScript>package
<syntaxhighlight lang="actionscript">package
{
{
public class Node
public class Node
Line 368: Line 368:
}
}
}
}
}</lang>
}</syntaxhighlight>
Usage:
Usage:
<lang ActionScript>import Node;
<syntaxhighlight lang="actionscript">import Node;


var A:Node = new Node(1);
var A:Node = new Node(1);
Line 376: Line 376:
var C:Node = new Node(3);
var C:Node = new Node(3);
A.insert(B);
A.insert(B);
A.insert(C);</lang>
A.insert(C);</syntaxhighlight>


=={{header|Ada}}==
=={{header|Ada}}==
We must create a context clause making the predefined generic procedure Ada.Unchecked_Deallocation visible to this program.
We must create a context clause making the predefined generic procedure Ada.Unchecked_Deallocation visible to this program.
<lang ada>with Ada.Unchecked_Deallocation;
<syntaxhighlight lang="ada">with Ada.Unchecked_Deallocation;
-- Define the link type
-- Define the link type
procedure Singly_Linked is
procedure Singly_Linked is
Line 413: Line 413:
Free(B);
Free(B);
Free(C);
Free(C);
end Singly_Linked;</lang>
end Singly_Linked;</syntaxhighlight>


=={{header|ALGOL 68}}==
=={{header|ALGOL 68}}==
Line 419: Line 419:
standard library. However Linked lists are presented in standard text
standard library. However Linked lists are presented in standard text
book examples. Or can be manually constructed, eg:
book examples. Or can be manually constructed, eg:
<lang algol68>MODE STRINGLIST = STRUCT(STRING value, REF STRINGLIST next);
<syntaxhighlight lang="algol68">MODE STRINGLIST = STRUCT(STRING value, REF STRINGLIST next);


STRINGLIST list := ("Big",
STRINGLIST list := ("Big",
Line 443: Line 443:
node := next OF node
node := next OF node
OD;
OD;
print((newline))</lang>
print((newline))</syntaxhighlight>
Output:<pre>Big fjords vex VERY quick waltz nymph </pre>
Output:<pre>Big fjords vex VERY quick waltz nymph </pre>


=={{header|ALGOL W}}==
=={{header|ALGOL W}}==
<lang algolw> % inserts a new value after the specified element of a list %
<syntaxhighlight lang="algolw"> % inserts a new value after the specified element of a list %
procedure insert( reference(ListI) value list
procedure insert( reference(ListI) value list
; integer value newValue
; integer value newValue
Line 460: Line 460:


% insert a new value into the list %
% insert a new value into the list %
insert( next(head), 4077 );</lang>
insert( next(head), 4077 );</syntaxhighlight>


=={{header|ARM Assembly}}==
=={{header|ARM Assembly}}==
{{works with|as|Raspberry Pi}}
{{works with|as|Raspberry Pi}}
<syntaxhighlight lang="arm assembly">
<lang ARM Assembly>
/* ARM assembly Raspberry PI */
/* ARM assembly Raspberry PI */
/* program insertList.s */
/* program insertList.s */
Line 644: Line 644:
bx lr @ leave function
bx lr @ leave function
iMagicNumber: .int 0xCCCCCCCD
iMagicNumber: .int 0xCCCCCCCD
</syntaxhighlight>
</lang>


=={{header|ATS}}==
=={{header|ATS}}==
Line 658: Line 658:
that the insertion routine will terminate.
that the insertion routine will 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 774: Line 774:


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


{{out}}
{{out}}
Line 783: Line 783:


=={{header|AutoHotkey}}==
=={{header|AutoHotkey}}==
<syntaxhighlight lang="autohotkey">a = 1
<lang AutoHotkey>a = 1
a_next = b
a_next = b
b = 2
b = 2
Line 799: Line 799:
%old%_next := new
%old%_next := new
%new%_next := temp
%new%_next := temp
}</lang>
}</syntaxhighlight>


=={{header|Axe}}==
=={{header|Axe}}==
<lang axe>Lbl INSERT
<syntaxhighlight lang="axe">Lbl INSERT
{r₁+2}ʳ→{r₂+2}ʳ
{r₁+2}ʳ→{r₂+2}ʳ
r₂→{r₁+2}ʳ
r₂→{r₁+2}ʳ
r₁
r₁
Return</lang>
Return</syntaxhighlight>


=={{header|BBC BASIC}}==
=={{header|BBC BASIC}}==
{{works with|BBC BASIC for Windows}}
{{works with|BBC BASIC for Windows}}
<lang bbcbasic> DIM node{pNext%, iData%}
<syntaxhighlight lang="bbcbasic"> DIM node{pNext%, iData%}
DIM a{} = node{}, b{} = node{}, c{} = node{}
DIM a{} = node{}, b{} = node{}, c{} = node{}
Line 825: Line 825:
here.pNext% = new{}
here.pNext% = new{}
ENDPROC
ENDPROC
</syntaxhighlight>
</lang>


=={{header|C}}==
=={{header|C}}==
Line 831: Line 831:
Define the method:
Define the method:


<lang c>void insert_append (struct link *anchor, struct link *newlink) {
<syntaxhighlight lang="c">void insert_append (struct link *anchor, struct link *newlink) {
newlink->next = anchor->next;
newlink->next = anchor->next;
anchor->next = newlink;
anchor->next = newlink;
}</lang>
}</syntaxhighlight>


Note that in a production implementation, one should check anchor and newlink to ensure they're valid values. (I.e., not NULL.)
Note that in a production implementation, one should check anchor and newlink to ensure they're valid values. (I.e., not NULL.)
Line 841: Line 841:


Create our links.
Create our links.
<lang c>struct link *a, *b, *c;
<syntaxhighlight lang="c">struct link *a, *b, *c;
a = malloc(sizeof(link));
a = malloc(sizeof(link));
b = malloc(sizeof(link));
b = malloc(sizeof(link));
Line 847: Line 847:
a->data = 1;
a->data = 1;
b->data = 2;
b->data = 2;
c->data = 3;</lang>
c->data = 3;</syntaxhighlight>


Prepare our initial list
Prepare our initial list
<lang c> insert_append (a, b);</lang>
<syntaxhighlight lang="c"> insert_append (a, b);</syntaxhighlight>


Insert element c after element a
Insert element c after element a
<lang c> insert_append (a, c);</lang>
<syntaxhighlight lang="c"> insert_append (a, c);</syntaxhighlight>


Remember to free the memory once we're done.
Remember to free the memory once we're done.
<lang c> free (a);
<syntaxhighlight lang="c"> free (a);
free (b);
free (b);
free (c);</lang>
free (c);</syntaxhighlight>


=={{header|C sharp|C#}}==
=={{header|C sharp|C#}}==
Line 864: Line 864:


Creates nodes and inserts them from the data passed.
Creates nodes and inserts them from the data passed.
<lang csharp>static void InsertAfter<T>(LinkedListNode<T> prev, T value)
<syntaxhighlight lang="csharp">static void InsertAfter<T>(LinkedListNode<T> prev, T value)
{
{
prev.Next = new Link() { Value = value, Next = prev.Next };
prev.Next = new Link() { Value = value, Next = prev.Next };
}</lang>
}</syntaxhighlight>


<lang csharp>static void Main()
<syntaxhighlight lang="csharp">static void Main()
{
{
//Create A(5)->B(7)
//Create A(5)->B(7)
Line 876: Line 876:
//Insert C between A and B
//Insert C between A and B
InsertAfter(A, 15);
InsertAfter(A, 15);
}</lang>
}</syntaxhighlight>


=={{header|C++}}==
=={{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.
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.


<lang cpp>template<typename T> void insert_after(link<T>* list_node, link<T>* new_node)
<syntaxhighlight lang="cpp">template<typename T> void insert_after(link<T>* list_node, link<T>* new_node)
{
{
new_node->next = list_node->next;
new_node->next = list_node->next;
list_node->next = new_node;
list_node->next = new_node;
};</lang>
};</syntaxhighlight>


Here's the example code using that method:
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.
The following code creates the links. As numeric values I've just taken the corresponding character values.
<lang cpp>link<int>* a = new link<int>('A', new link<int>('B'));
<syntaxhighlight lang="cpp">link<int>* a = new link<int>('A', new link<int>('B'));
link<int>* c = new link<int>('C');</lang>
link<int>* c = new link<int>('C');</syntaxhighlight>


Now insert c after a:
Now insert c after a:
<lang cpp> insert_after(a, c);</lang>
<syntaxhighlight lang="cpp"> insert_after(a, c);</syntaxhighlight>


Finally destroy the list:
Finally destroy the list:
<lang cpp>while (a)
<syntaxhighlight lang="cpp">while (a)
{
{
link<int>* tmp = a;
link<int>* tmp = a;
a = a->next;
a = a->next;
delete tmp;
delete tmp;
}</lang>
}</syntaxhighlight>


=={{header|Clojure}}==
=={{header|Clojure}}==


<lang lisp>(defn insert-after [new old ls]
<syntaxhighlight lang="lisp">(defn insert-after [new old ls]
(cond (empty? ls) ls
(cond (empty? ls) ls
(= (first ls) old) (cons old (cons new (rest ls)))
(= (first ls) old) (cons old (cons new (rest ls)))
:else (cons (first ls) (insert-after new old (rest ls)))))</lang>
:else (cons (first ls) (insert-after new old (rest ls)))))</syntaxhighlight>


And the test:
And the test:
<lang lisp>user=> (insert-after 'c 'a '(a b))
<syntaxhighlight lang="lisp">user=> (insert-after 'c 'a '(a b))
(a c b)</lang>
(a c b)</syntaxhighlight>


=={{header|Common Lisp}}==
=={{header|Common Lisp}}==
Line 919: 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.
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.


<lang lisp>(defun insert-after (new-element old-element list &key (test 'eql))
<syntaxhighlight lang="lisp">(defun insert-after (new-element old-element list &key (test 'eql))
"Return a list like list, but with new-element appearing after the
"Return a list like list, but with new-element appearing after the
first occurence of old-element. If old-element does not appear in
first occurence of old-element. If old-element does not appear in
Line 937: Line 937:
((or (null next) (funcall test old-element (car prev)))
((or (null next) (funcall test old-element (car prev)))
(rplacd prev (cons new-element next))
(rplacd prev (cons new-element next))
list))))</lang>
list))))</syntaxhighlight>


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.
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.


<lang lisp>(defun simple-insert-after (new-element old-element list &key (test 'eql))
<syntaxhighlight lang="lisp">(defun simple-insert-after (new-element old-element list &key (test 'eql))
(let ((tail (rest (member old-element list :test test))))
(let ((tail (rest (member old-element list :test test))))
(nconc (ldiff list tail)
(nconc (ldiff list tail)
(cons new-element tail))))</lang>
(cons new-element tail))))</syntaxhighlight>


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.)
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.)


<lang lisp>(defun insert-after (list new existing &key (test #'eql))
<syntaxhighlight lang="lisp">(defun insert-after (list new existing &key (test #'eql))
"Insert item new into list, before existing, or at the end if existing
"Insert item new into list, before existing, or at the end if existing
is not present. The default comparison test function is EQL. This
is not present. The default comparison test function is EQL. This
Line 962: Line 962:
;; and make that list the new rest.
;; and make that list the new rest.
(t (rplacd list (insert-before (cdr list) new existing :test test))
(t (rplacd list (insert-before (cdr list) new existing :test test))
list)))</lang>
list)))</syntaxhighlight>


=={{header|D}}==
=={{header|D}}==
<lang d>struct SLinkedNode(T) {
<syntaxhighlight lang="d">struct SLinkedNode(T) {
T data;
T data;
typeof(this)* next;
typeof(this)* next;
Line 985: Line 985:


// The GC will collect the memory.
// The GC will collect the memory.
}</lang>
}</syntaxhighlight>


=={{header|Delphi}}==
=={{header|Delphi}}==
Line 991: 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 (* ... *).
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 (* ... *).


<lang delphi>// Using the same type defs from the one way list example.
<syntaxhighlight lang="delphi">// Using the same type defs from the one way list example.


Type
Type
Line 1,048: Line 1,048:
CurrentNode.Next := result ;
CurrentNode.Next := result ;
end;
end;
end;</lang>
end;</syntaxhighlight>


=={{header|E}}==
=={{header|E}}==


<lang e>def insertAfter(head :LinkedList ? (!head.null()),
<syntaxhighlight lang="e">def insertAfter(head :LinkedList ? (!head.null()),
new :LinkedList ? (new.next().null())) {
new :LinkedList ? (new.next().null())) {
new.setNext(head.next())
new.setNext(head.next())
Line 1,069: Line 1,069:
println(x.value())
println(x.value())
x := x.next()
x := x.next()
}</lang>
}</syntaxhighlight>


=={{header|EchoLisp}}==
=={{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.
Lists are mutable, and we use the destructive - and dangerous - set-cdr! operator which modifies the 'rest' part of a list or sub-list.
<lang lisp>
<syntaxhighlight lang="lisp">
(define (insert-after lst target item)
(define (insert-after lst target item)
(when (null? lst) (error "cannot insert in" null))
(when (null? lst) (error "cannot insert in" null))
Line 1,085: Line 1,085:
(insert-after L 'x 'y)
(insert-after L 'x 'y)
L → (a c b y)
L → (a c b y)
</syntaxhighlight>
</lang>


=={{header|Elena}}==
=={{header|Elena}}==
<lang elena>singleton linkHelper
<syntaxhighlight lang="elena">singleton linkHelper
{
{
insertAfter(Link prev, IntNumber i)
insertAfter(Link prev, IntNumber i)
Line 1,094: Line 1,094:
prev.Next := new Link(i, prev.Next)
prev.Next := new Link(i, prev.Next)
}
}
}</lang>
}</syntaxhighlight>


=={{header|Erlang}}==
=={{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:
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">
<lang Erlang>
-module( singly_linked_list ).
-module( singly_linked_list ).


Line 1,150: Line 1,150:
loop_foreach( _Fun, nonext ) -> ok;
loop_foreach( _Fun, nonext ) -> ok;
loop_foreach( Fun, Next ) -> Next ! {foreach, Fun}.
loop_foreach( Fun, Next ) -> Next ! {foreach, Fun}.
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 1,160: Line 1,160:


=={{header|Factor}}==
=={{header|Factor}}==
<lang factor>: list-append ( previous new -- )
<syntaxhighlight lang="factor">: list-append ( previous new -- )
[ swap next>> >>next drop ] [ >>next drop ] 2bi ;
[ swap next>> >>next drop ] [ >>next drop ] 2bi ;


Line 1,168: Line 1,168:
[ C <linked-list> list-append ] keep
[ C <linked-list> list-append ] keep
[ B <linked-list> list-append ] keep
[ B <linked-list> list-append ] keep
.</lang>
.</syntaxhighlight>
Output:
Output:
<pre>
<pre>
Line 1,186: Line 1,186:
Extending Node class from [[Singly-Linked_List_(element)]]:
Extending Node class from [[Singly-Linked_List_(element)]]:


<lang fantom>
<syntaxhighlight lang="fantom">
class Node
class Node
{
{
Line 1,221: Line 1,221:
}
}
}
}
</syntaxhighlight>
</lang>


Output:
Output:
Line 1,233: Line 1,233:


Using the linked list concept described in the [[Singly-Linked_List_(element)]] topic:
Using the linked list concept described in the [[Singly-Linked_List_(element)]] topic:
<lang forth>\ Create the list and some list elements
<syntaxhighlight lang="forth">\ Create the list and some list elements
create A 0 , char A ,
create A 0 , char A ,
create B 0 , char B ,
create B 0 , char B ,
create C 0 , char C ,</lang>
create C 0 , char C ,</syntaxhighlight>


Now insert b after a and c after b, giving a->b->c
Now insert b after a and c after b, giving a->b->c
<lang forth>B A chain
<syntaxhighlight lang="forth">B A chain
C B chain</lang>
C B chain</syntaxhighlight>


Here is an abbreviated version of the definition of 'chain' from the other article:
Here is an abbreviated version of the definition of 'chain' from the other article:
<lang forth> : chain ( a b -- ) 2dup @ swap ! ! ;</lang>
<syntaxhighlight lang="forth"> : chain ( a b -- ) 2dup @ swap ! ! ;</syntaxhighlight>


=={{header|Fortran}}==
=={{header|Fortran}}==
In ISO Fortran 95 or later:
In ISO Fortran 95 or later:
<lang fortran>elemental subroutine addAfter(nodeBefore,value)
<syntaxhighlight lang="fortran">elemental subroutine addAfter(nodeBefore,value)
type (node), intent(inout) :: nodeBefore
type (node), intent(inout) :: nodeBefore
real, intent(in) :: value
real, intent(in) :: value
Line 1,256: Line 1,256:
newNode%next => nodeBefore%next
newNode%next => nodeBefore%next
nodeBefore%next => newNode
nodeBefore%next => newNode
end subroutine addAfter</lang>
end subroutine addAfter</syntaxhighlight>


=={{header|FreeBASIC}}==
=={{header|FreeBASIC}}==
Assumes you already have the ll_int data type, defined [[Singly-linked_list/Element_definition#FreeBASIC|here]].
Assumes you already have the ll_int data type, defined [[Singly-linked_list/Element_definition#FreeBASIC|here]].
<lang freebasic>sub insert_ll_int( anchor as ll_int ptr, ins as ll_int ptr)
<syntaxhighlight lang="freebasic">sub insert_ll_int( anchor as ll_int ptr, ins as ll_int ptr)
ins->nxt = anchor->nxt
ins->nxt = anchor->nxt
anchor->nxt = ins
anchor->nxt = ins
end sub</lang>
end sub</syntaxhighlight>


=={{header|Go}}==
=={{header|Go}}==
<lang go>package main
<syntaxhighlight lang="go">package main


import "fmt"
import "fmt"
Line 1,303: Line 1,303:
h.insert("C")
h.insert("C")
h.printList()
h.printList()
}</lang>
}</syntaxhighlight>
Output:
Output:
<pre>
<pre>
Line 1,312: Line 1,312:
=={{header|Groovy}}==
=={{header|Groovy}}==
Solution (uses ListNode from [[Singly-Linked List (element)#Groovy]]):
Solution (uses ListNode from [[Singly-Linked List (element)#Groovy]]):
<lang groovy>class NodeList {
<syntaxhighlight lang="groovy">class NodeList {
private enum Flag { FRONT }
private enum Flag { FRONT }
private ListNode head
private ListNode head
Line 1,331: Line 1,331:
}
}
String toString() { "${head}" }
String toString() { "${head}" }
}</lang>
}</syntaxhighlight>


Test:
Test:
<lang groovy>def list = new NodeList()
<syntaxhighlight lang="groovy">def list = new NodeList()
list.insert('B')
list.insert('B')
list.insert('A')
list.insert('A')
Line 1,340: Line 1,340:


list.insert('C', 'A')
list.insert('C', 'A')
println list</lang>
println list</syntaxhighlight>


Output:
Output:
Line 1,348: Line 1,348:
=={{header|Haskell}}==
=={{header|Haskell}}==
This kind of list manipulation is [[unidiomatic]] Haskell. But you can try the following:
This kind of list manipulation is [[unidiomatic]] Haskell. But you can try the following:
<lang haskell>insertAfter a b (c:cs) | a==c = a : b : cs
<syntaxhighlight lang="haskell">insertAfter a b (c:cs) | a==c = a : b : cs
| otherwise = c : insertAfter a b cs
| otherwise = c : insertAfter a b cs
insertAfter _ _ [] = error "Can't insert"</lang>
insertAfter _ _ [] = error "Can't insert"</syntaxhighlight>


==Icon and Unicon==
==Icon and Unicon==
Line 1,358: Line 1,358:
==={{header|Icon}}===
==={{header|Icon}}===


<syntaxhighlight lang="icon">
<lang Icon>
record Node (value, successor)
record Node (value, successor)


Line 1,365: Line 1,365:
node.successor := newNode
node.successor := newNode
end
end
</syntaxhighlight>
</lang>


==={{header|Unicon}}===
==={{header|Unicon}}===


<syntaxhighlight lang="unicon">
<lang Unicon>
class Node (value, successor)
class Node (value, successor)


Line 1,381: Line 1,381:
self.successor := successor
self.successor := successor
end
end
</syntaxhighlight>
</lang>


=={{header|J}}==
=={{header|J}}==


<lang J>list=: 1 65,:_ 66
<syntaxhighlight lang="j">list=: 1 65,:_ 66
A=:0 NB. reference into list
A=:0 NB. reference into list
B=:1 NB. reference into list
B=:1 NB. reference into list
Line 1,395: Line 1,395:
localNewNode=: (localOldLinkRef { localListValue), localNewValue
localNewNode=: (localOldLinkRef { localListValue), localNewValue
(localListName)=: (localNewLinkRef localOldLinkRef} localListValue), localNewNode
(localListName)=: (localNewLinkRef localOldLinkRef} localListValue), localNewNode
)</lang>
)</syntaxhighlight>


With these definitions:
With these definitions:
Line 1,407: Line 1,407:
=={{header|Java}}==
=={{header|Java}}==
Extending [[Singly-Linked_List_(element)#Java]]
Extending [[Singly-Linked_List_(element)#Java]]
<lang Java>void insertNode(Node<T> anchor_node, Node<T> new_node)
<syntaxhighlight lang="java">void insertNode(Node<T> anchor_node, Node<T> new_node)
{
{
new_node.next = anchor_node.next;
new_node.next = anchor_node.next;
anchor_node.next = new_node;
anchor_node.next = new_node;
}</lang>
}</syntaxhighlight>
{{works with|Java|1.5+}}
{{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).
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: Line 1,417:
=={{header|JavaScript}}==
=={{header|JavaScript}}==
Extending [[Singly-Linked_List_(element)#JavaScript]]
Extending [[Singly-Linked_List_(element)#JavaScript]]
<lang javascript>LinkedList.prototype.insertAfter = function(searchValue, nodeToInsert) {
<syntaxhighlight lang="javascript">LinkedList.prototype.insertAfter = function(searchValue, nodeToInsert) {
if (this._value == searchValue) {
if (this._value == searchValue) {
nodeToInsert.next(this.next());
nodeToInsert.next(this.next());
Line 1,428: Line 1,428:
}
}
var list = createLinkedListFromArray(['A','B']);
var list = createLinkedListFromArray(['A','B']);
list.insertAfter('A', new LinkedList('C', null));</lang>
list.insertAfter('A', new LinkedList('C', null));</syntaxhighlight>


=={{header|jq}}==
=={{header|jq}}==
Line 1,437: Line 1,437:
see [[Singly-linked_list/Element_definition#jq]].
see [[Singly-linked_list/Element_definition#jq]].


<lang jq> def new($item; $next):
<syntaxhighlight lang="jq"> def new($item; $next):
if $next | (.==null or is_singly_linked_list)
if $next | (.==null or is_singly_linked_list)
then {$item, $next}
then {$item, $next}
Line 1,447: Line 1,447:


def insert($x):
def insert($x):
.next |= new($x; .);</lang>
.next |= new($x; .);</syntaxhighlight>
'''An example''':
'''An example''':
<syntaxhighlight lang="jq">
<lang jq>
new(1) | insert(2)
new(1) | insert(2)
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 1,467: Line 1,467:
See the <tt>LinkedList</tt> implemented at [[Singly-linked_list/Element_definition#Julia]].
See the <tt>LinkedList</tt> implemented at [[Singly-linked_list/Element_definition#Julia]].


<lang julia>function Base.insert!(ll::LinkedList{T}, index::Integer, item::T) where T
<syntaxhighlight lang="julia">function Base.insert!(ll::LinkedList{T}, index::Integer, item::T) where T
if index == 1
if index == 1
if isempty(ll)
if isempty(ll)
Line 1,487: Line 1,487:
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,516: Line 1,516:
insertAfter(a, c)
insertAfter(a, c)
println("After insertion : $a")
println("After insertion : $a")
}</lang>
}</syntaxhighlight>


{{out}}
{{out}}
Line 1,525: Line 1,525:


=={{header|Logo}}==
=={{header|Logo}}==
<lang logo>to insert :after :list :value
<syntaxhighlight lang="logo">to insert :after :list :value
localmake "tail member :after :list
localmake "tail member :after :list
if not empty? :tail [.setbf :tail fput :value bf :tail]
if not empty? :tail [.setbf :tail fput :value bf :tail]
Line 1,531: Line 1,531:
end
end


show insert 5 [3 5 1 8] 2</lang>
show insert 5 [3 5 1 8] 2</syntaxhighlight>
[3 5 2 1 8]
[3 5 2 1 8]


=={{header|Mathematica}}/{{header|Wolfram Language}}==
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<lang Mathematica>Append[{a, b}, c]
<syntaxhighlight lang="mathematica">Append[{a, b}, c]
->{a, b, c}</lang>
->{a, b, c}</syntaxhighlight>


=={{header|Modula-3}}==
=={{header|Modula-3}}==
<lang modula3>MODULE SinglyLinkedList EXPORTS Main;
<syntaxhighlight lang="modula3">MODULE SinglyLinkedList EXPORTS Main;


TYPE
TYPE
Line 1,564: Line 1,564:
InsertAppend(a, b);
InsertAppend(a, b);
InsertAppend(a, c)
InsertAppend(a, c)
END SinglyLinkedList.</lang>
END SinglyLinkedList.</syntaxhighlight>


=={{header|Nim}}==
=={{header|Nim}}==
<lang nim>type Node[T] = ref object
<syntaxhighlight lang="nim">type Node[T] = ref object
next: Node[T]
next: Node[T]
data: T
data: T
Line 1,583: Line 1,583:


a.insertAppend(b)
a.insertAppend(b)
b.insertAppend(c)</lang>
b.insertAppend(c)</syntaxhighlight>


=={{header|OCaml}}==
=={{header|OCaml}}==
This kind of list manipulation is unidiomatic OCaml. But you can try the following:
This kind of list manipulation is unidiomatic OCaml. But you can try the following:
<lang ocaml>let rec insert_after a b = function
<syntaxhighlight lang="ocaml">let rec insert_after a b = function
c :: cs when a = c -> a :: b :: cs
c :: cs when a = c -> a :: b :: cs
| c :: cs -> c :: insert_after a b cs
| c :: cs -> c :: insert_after a b cs
| [] -> raise Not_found</lang>
| [] -> raise Not_found</syntaxhighlight>


=={{header|Oforth}}==
=={{header|Oforth}}==
Line 1,596: 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).
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).


<lang Oforth>Collection Class new: LinkedList(data, mutable next)
<syntaxhighlight lang="oforth">Collection Class new: LinkedList(data, mutable next)


LinkedList method: initialize := next := data ;
LinkedList method: initialize := next := data ;
Line 1,611: Line 1,611:
: testLink LinkedList new($A, null) dup add($B) dup add($C) ;
: testLink LinkedList new($A, null) dup add($B) dup add($C) ;


testLink println</lang>
testLink println</syntaxhighlight>


{{out}}
{{out}}
Line 1,620: Line 1,620:
=={{header|ooRexx}}==
=={{header|ooRexx}}==
See [[Singly-linked_list/Element_definition#ooRexx|Single-linked list/Element definition]] for full class definition.
See [[Singly-linked_list/Element_definition#ooRexx|Single-linked list/Element definition]] for full class definition.
<syntaxhighlight lang="oorexx">
<lang ooRexx>
list = .linkedlist~new
list = .linkedlist~new
index = list~insert("abc") -- insert a first item, keeping the index
index = list~insert("abc") -- insert a first item, keeping the index
Line 1,627: Line 1,627:
list~insert("456", index) -- inserts between "abc" and "def"
list~insert("456", index) -- inserts between "abc" and "def"
list~remove(index) -- removes "abc"
list~remove(index) -- removes "abc"
</syntaxhighlight>
</lang>


=={{header|Pascal}}==
=={{header|Pascal}}==
Line 1,634: 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.
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.


<lang pascal>type
<syntaxhighlight lang="pascal">type
pCharNode = ^CharNode;
pCharNode = ^CharNode;
CharNode = record
CharNode = record
Line 1,648: Line 1,648:
newnode^.next := listnode^.next;
newnode^.next := listnode^.next;
listnode^.next := newnode;
listnode^.next := newnode;
end;</lang>
end;</syntaxhighlight>
Usage example:
Usage example:
<lang pascal>var
<syntaxhighlight lang="pascal">var
A, B: pCharNode;
A, B: pCharNode;
begin
begin
Line 1,676: Line 1,676:
dispose(B);
dispose(B);
end
end
end.</lang>
end.</syntaxhighlight>


=={{header|Perl}}==
=={{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.
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.
<lang perl>my @l = ($A, $B);
<syntaxhighlight lang="perl">my @l = ($A, $B);
push @l, $C, splice @l, 1;</lang>
push @l, $C, splice @l, 1;</syntaxhighlight>
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.
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.
<lang perl>sub insert_after {
<syntaxhighlight lang="perl">sub insert_after {
# first argument: node to insert after
# first argument: node to insert after
# second argument: node to insert
# second argument: node to insert
Line 1,701: Line 1,701:
data => 2,
data => 2,
);
);
insert_after \%A, \%C;</lang>
insert_after \%A, \%C;</syntaxhighlight>
Note that you don't have to name your new nodes. The following works just as well:
Note that you don't have to name your new nodes. The following works just as well:
<lang perl> insert_after \%A, { data => 2 };</lang>
<syntaxhighlight lang="perl"> insert_after \%A, { data => 2 };</syntaxhighlight>
Note the curly braces instead of round parentheses.
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:
It is straightforward to extend the function to take an arbitrary number of list nodes to insert:
<lang perl>sub insert_after {
<syntaxhighlight lang="perl">sub insert_after {
my $node = $_[0];
my $node = $_[0];
my $next = $node->{next};
my $next = $node->{next};
Line 1,717: Line 1,717:
}
}
$node->{next} = $next;
$node->{next} = $next;
}</lang>
}</syntaxhighlight>
With this, it's rather easy to build a list:
With this, it's rather easy to build a list:
<lang perl>my %list = ( data => 'A' );
<syntaxhighlight lang="perl">my %list = ( data => 'A' );
insert_after \%list, { data => 'B' }, { data => 'C' };</lang>
insert_after \%list, { data => 'B' }, { data => 'C' };</syntaxhighlight>
List handling is simplified if the variables themselves contain references. For example:
List handling is simplified if the variables themselves contain references. For example:
<lang perl>my $list2;
<syntaxhighlight lang="perl">my $list2;


# create a new list ('A'. 'B', 'C') and store it in $list2
# create a new list ('A'. 'B', 'C') and store it in $list2
Line 1,731: Line 1,731:


# append new nodes ('A2a', 'A2b') after the second element (which now is 'A2')
# append new nodes ('A2a', 'A2b') after the second element (which now is 'A2')
insert_after $list2->{next}, { data => 'A2a' }, { data => 'A2b' };</lang>
insert_after $list2->{next}, { data => 'A2a' }, { data => 'A2b' };</syntaxhighlight>


=={{header|Phix}}==
=={{header|Phix}}==
See also [[Singly-linked_list/Traversal#Phix|Traversal]] and [[Singly-linked_list/Element_removal#Phix|Removal]].
See also [[Singly-linked_list/Traversal#Phix|Traversal]] and [[Singly-linked_list/Element_removal#Phix|Removal]].
<!--<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,751: Line 1,751:
<span style="color: #0000FF;">?</span><span style="color: #000000;">sll</span>
<span style="color: #0000FF;">?</span><span style="color: #000000;">sll</span>
<!--</lang>-->
<!--</syntaxhighlight>-->
{{out}}
{{out}}
<pre>
<pre>
Line 1,759: Line 1,759:
=={{header|PicoLisp}}==
=={{header|PicoLisp}}==
Destructive operation
Destructive operation
<lang PicoLisp>(de insertAfter (Item Lst New)
<syntaxhighlight lang="picolisp">(de insertAfter (Item Lst New)
(when (member Item Lst)
(when (member Item Lst)
(con @ (cons New (cdr @))) )
(con @ (cons New (cdr @))) )
Lst )</lang>
Lst )</syntaxhighlight>
Non-destructive operation
Non-destructive operation
<lang PicoLisp>(de insertAfter (Item Lst New)
<syntaxhighlight lang="picolisp">(de insertAfter (Item Lst New)
(if (index Item Lst)
(if (index Item Lst)
(conc (cut @ 'Lst) (cons New Lst))
(conc (cut @ 'Lst) (cons New Lst))
Lst ) )</lang>
Lst ) )</syntaxhighlight>
Output in both cases:
Output in both cases:
<pre>: (insertAfter 'A '(A B) 'C)
<pre>: (insertAfter 'A '(A B) 'C)
Line 1,776: Line 1,776:


=={{header|PL/I}}==
=={{header|PL/I}}==
<syntaxhighlight lang="pl/i">
<lang PL/I>
/* Let H be a pointer to a node in a one-way-linked list. */
/* 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. */
/* Insert an element, whose value is given by variable V, following that node. */
Line 1,784: Line 1,784:
node.value = V;
node.value = V;
H->p = Q; /* Break the list at H, and point it at the new node. */
H->p = Q; /* Break the list at H, and point it at the new node. */
</syntaxhighlight>
</lang>


=={{header|Pop11}}==
=={{header|Pop11}}==
Line 1,790: Line 1,790:
In Pop11 one normally uses built-in lists:
In Pop11 one normally uses built-in lists:


<lang pop11>define insert_into_list(anchor, x);
<syntaxhighlight lang="pop11">define insert_into_list(anchor, x);
cons(x, back(anchor)) -> back(anchor);
cons(x, back(anchor)) -> back(anchor);
enddefine;
enddefine;
Line 1,797: Line 1,797:
insert_into_list(l1, "b");
insert_into_list(l1, "b");
;;; insert c
;;; insert c
insert_into_list(l1, "c");</lang>
insert_into_list(l1, "c");</syntaxhighlight>


If one wants one can use user-defined list node (for convenience we repeat definition of list node):
If one wants one can use user-defined list node (for convenience we repeat definition of list node):


<lang pop11>uses objectclass;
<syntaxhighlight lang="pop11">uses objectclass;
define :class ListNode;
define :class ListNode;
slot value = [];
slot value = [];
Line 1,814: Line 1,814:
insert_into_List(l2, "b");
insert_into_List(l2, "b");
;;; insert c
;;; insert c
insert_into_List(l2, "c");</lang>
insert_into_List(l2, "c");</syntaxhighlight>


Note that user-defined case differs from built-in case only because of names.
Note that user-defined case differs from built-in case only because of names.


=={{header|PureBasic}}==
=={{header|PureBasic}}==
<lang PureBasic>Procedure insertAfter(Value, *node.MyData = #Null)
<syntaxhighlight lang="purebasic">Procedure insertAfter(Value, *node.MyData = #Null)
Protected *newNode.MyData = AllocateMemory(SizeOf(MyData))
Protected *newNode.MyData = AllocateMemory(SizeOf(MyData))
If *newNode
If *newNode
Line 1,836: Line 1,836:
*SL_List = insertAfter(a) ;start the list
*SL_List = insertAfter(a) ;start the list
insertAfter(b, *SL_List) ;insert after head of list
insertAfter(b, *SL_List) ;insert after head of list
insertAfter(c, *SL_List) ;insert after head of list and before tail</lang>
insertAfter(c, *SL_List) ;insert after head of list and before tail</syntaxhighlight>


=={{header|Python}}==
=={{header|Python}}==
<lang python>def chain_insert(lst, at, item):
<syntaxhighlight lang="python">def chain_insert(lst, at, item):
while lst is not None:
while lst is not None:
if lst[0] == at:
if lst[0] == at:
Line 1,850: Line 1,850:
chain = ['A', ['B', None]]
chain = ['A', ['B', None]]
chain_insert(chain, 'A', 'C')
chain_insert(chain, 'A', 'C')
print chain</lang>
print chain</syntaxhighlight>
Output:
Output:
<lang python>['A', ['C', ['B', None]]]</lang>
<syntaxhighlight lang="python">['A', ['C', ['B', None]]]</syntaxhighlight>


=={{header|Racket}}==
=={{header|Racket}}==


<syntaxhighlight lang="racket">
<lang Racket>
#lang racket
#lang racket


Line 1,868: Line 1,868:
(insert-after! l 2 2.5)
(insert-after! l 2 2.5)
l ; -> (mcons 1 (mcons 2 (mcons 2.5 (mcons 3))))
l ; -> (mcons 1 (mcons 2 (mcons 2.5 (mcons 3))))
</syntaxhighlight>
</lang>


=={{header|Raku}}==
=={{header|Raku}}==
Line 1,875: Line 1,875:
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 insert ($value) {
<syntaxhighlight lang="raku" line> method insert ($value) {
$.next = Cell.new(:$value, :$.next)
$.next = Cell.new(:$value, :$.next)
}</lang>
}</syntaxhighlight>


=={{header|REXX}}==
=={{header|REXX}}==
<lang rexx>/*REXX program demonstrates how to create and show a single-linked list.*/
<syntaxhighlight lang="rexx">/*REXX program demonstrates how to create and show a single-linked list.*/
@.=0 /*define a null linked list. */
@.=0 /*define a null linked list. */
call set@ 3 /*linked list: 12 Proth primes. */
call set@ 3 /*linked list: 12 Proth primes. */
Line 1,933: Line 1,933:
@..y=n /*set a locator pointer to self. */
@..y=n /*set a locator pointer to self. */
@.max_width=max(@.max_width,length(y)) /*set maximum width of any value.*/
@.max_width=max(@.max_width,length(y)) /*set maximum width of any value.*/
return /*return to invoker of this sub. */</lang>
return /*return to invoker of this sub. */</syntaxhighlight>
'''output'''
'''output'''
<pre>
<pre>
Line 1,971: Line 1,971:


=={{header|Ruby}}==
=={{header|Ruby}}==
<lang ruby>class ListNode
<syntaxhighlight lang="ruby">class ListNode
def insert_after(search_value, new_value)
def insert_after(search_value, new_value)
if search_value == value
if search_value == value
Line 1,984: Line 1,984:


list = ListNode.new(:a, ListNode.new(:b))
list = ListNode.new(:a, ListNode.new(:b))
list.insert_after(:a, :c)</lang>
list.insert_after(:a, :c)</syntaxhighlight>


=={{header|Rust}}==
=={{header|Rust}}==


Extending [[Singly-Linked List (element)#Rust]]. Please see that page for the Linked List struct declarations.
Extending [[Singly-Linked List (element)#Rust]]. Please see that page for the Linked List struct declarations.
<lang rust>impl<T> List<T> {
<syntaxhighlight lang="rust">impl<T> List<T> {
pub fn new() -> Self {
pub fn new() -> Self {
List { head: None }
List { head: None }
Line 2,000: Line 2,000:
});
});
self.head = Some(new_node);
self.head = Some(new_node);
}</lang>
}</syntaxhighlight>


=={{header|Scala}}==
=={{header|Scala}}==
In Scala (and functional programming) we create a new list instead of modifying existing one.
In Scala (and functional programming) we create a new list instead of modifying existing one.
<lang scala>
<syntaxhighlight lang="scala">
/*
/*
Here is a basic list definition
Here is a basic list definition
Line 2,016: Line 2,016:
def add[A](as: List[A], a: A): List[A] = Cons(a, as)
def add[A](as: List[A], a: A): List[A] = Cons(a, as)
}
}
</syntaxhighlight>
</lang>


=={{header|Scheme}}==
=={{header|Scheme}}==
Non-mutating:
Non-mutating:
<lang scheme>(define (insert-after a b lst)
<syntaxhighlight lang="scheme">(define (insert-after a b lst)
(if (null? lst)
(if (null? lst)
lst ; This should be an error, but we will just return the list untouched
lst ; This should be an error, but we will just return the list untouched
Line 2,027: Line 2,027:
(if (equal? a c)
(if (equal? a c)
(cons a (cons b cs))
(cons a (cons b cs))
(cons c (insert-after a b cs))))))</lang>
(cons c (insert-after a b cs))))))</syntaxhighlight>


Mutating:
Mutating:
<lang scheme>(define (insert-after! a b lst)
<syntaxhighlight lang="scheme">(define (insert-after! a b lst)
(let ((pos (member a lst)))
(let ((pos (member a lst)))
(if pos
(if pos
(set-cdr! pos (cons b (cdr pos))))))</lang>
(set-cdr! pos (cons b (cdr pos))))))</syntaxhighlight>


=={{header|Sidef}}==
=={{header|Sidef}}==
<lang ruby>func insert_after(a,b) {
<syntaxhighlight lang="ruby">func insert_after(a,b) {
b{:next} = a{:next};
b{:next} = a{:next};
a{:next} = b;
a{:next} = b;
Line 2,053: Line 2,053:
);
);


insert_after(A, C);</lang>
insert_after(A, C);</syntaxhighlight>


=={{header|Stata}}==
=={{header|Stata}}==
Line 2,067: Line 2,067:
No error checking is included.
No error checking is included.


<lang tcl>
<syntaxhighlight lang="tcl">
proc insertIntoList {existingList predecessor newElement} {
proc insertIntoList {existingList predecessor newElement} {
upvar $existingList exList
upvar $existingList exList
Line 2,076: Line 2,076:
insertIntoList list A C
insertIntoList list A C
puts $list
puts $list
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 2,084: Line 2,084:
=={{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(["A", "B"])
var ll = LinkedList.new(["A", "B"])
ll.insertAfter("A", "C")
ll.insertAfter("A", "C")
System.print(ll)</lang>
System.print(ll)</syntaxhighlight>


{{out}}
{{out}}
Line 2,096: Line 2,096:


=={{header|X86 Assembly}}==
=={{header|X86 Assembly}}==
<lang x86asm>
<syntaxhighlight lang="x86asm">
; x86_64 Linux NASM
; x86_64 Linux NASM
; Linked_List_Insert.asm
; Linked_List_Insert.asm
Line 2,126: Line 2,126:


%endif
%endif
</syntaxhighlight>
</lang>


=={{header|XPL0}}==
=={{header|XPL0}}==
<lang XPL0>def \Node\ Link, Data; \linked list element definition
<syntaxhighlight lang="xpl0">def \Node\ Link, Data; \linked list element definition
def IntSize = 4; \number of bytes in an integer
def IntSize = 4; \number of bytes in an integer


Line 2,156: Line 2,156:
MyNode:= MyNode(Link); \move to next node
MyNode:= MyNode(Link); \move to next node
];
];
]</lang>
]</syntaxhighlight>


{{out}}
{{out}}
Line 2,164: Line 2,164:


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


Line 2,224: Line 2,224:
printNode(1)
printNode(1)
printNode(2)
printNode(2)
printNode(3)</lang>{{out}}
printNode(3)</syntaxhighlight>{{out}}
<pre>1000
<pre>1000
3000
3000
Line 2,232: Line 2,232:
=={{header|zkl}}==
=={{header|zkl}}==
In place:
In place:
<lang zkl>L("a","b","c").insert(1,"foo") //-->L("a","foo","b","c")
<syntaxhighlight lang="zkl">L("a","b","c").insert(1,"foo") //-->L("a","foo","b","c")
a:=L("a","b","c"); a.insert(a.find("b"),"foo") //-->L("a","foo","b","c")</lang>
a:=L("a","b","c"); a.insert(a.find("b"),"foo") //-->L("a","foo","b","c")</syntaxhighlight>
Create a new list:
Create a new list:
<lang zkl>a:=ROList("a","b","c");
<syntaxhighlight lang="zkl">a:=ROList("a","b","c");
n:=a.index("b"); a[0,n].append("foo").extend(a[n,*]) //-->ROList("a","foo","b","c")</lang>
n:=a.index("b"); a[0,n].append("foo").extend(a[n,*]) //-->ROList("a","foo","b","c")</syntaxhighlight>


=={{header|Zig}}==
=={{header|Zig}}==
<lang zig>
<syntaxhighlight lang="zig">
const std = @import("std");
const std = @import("std");


Line 2,282: Line 2,282:
};
};
}
}
</syntaxhighlight>
</lang>


Create a new list:
Create a new list:


<lang zig>
<syntaxhighlight lang="zig">
var l1 = LinkedList(i32).init();
var l1 = LinkedList(i32).init();
</syntaxhighlight>
</lang>


Add element:
Add element:


<lang zig>
<syntaxhighlight lang="zig">
try list.add(1);
try list.add(1);
</syntaxhighlight>
</lang>