Singly-linked list/Element insertion: Difference between revisions

m
m (→‎{{header|Wren}}: Minor tidy)
 
(10 intermediate revisions by 8 users not shown)
Line 8:
=={{header|360 Assembly}}==
The program uses one ASSIST macro (XPRNT) to keep the code as short as possible.
<langsyntaxhighlight lang="360asm">* Singly-linked list - Insert after 01/02/2017
LISTSINA CSECT
USING LISTSINA,R13 base register
Line 94:
NEXT DS A
YREGS
END LISTSINA</langsyntaxhighlight>
{{out}}
<pre>
Line 104:
=={{header|AArch64 Assembly}}==
{{works with|as|Raspberry Pi 3B version Buster 64 bits}}
<syntaxhighlight lang="aarch64 assembly">
<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>
</lang>
 
=={{header|ACL2}}==
<langsyntaxhighlight Lisplang="lisp">(defun insert-after (x e xs)
(cond ((endp xs)
nil)
Line 239:
(cons e (rest xs))))
(t (cons (first xs)
(insert-after x e (rest xs))))))</langsyntaxhighlight>
 
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}}
<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 338:
TestAddAfter('C,listBegin)
TestClear()
RETURN</langsyntaxhighlight>
{{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:
<langsyntaxhighlight ActionScriptlang="actionscript">package
{
public class Node
Line 368:
}
}
}</langsyntaxhighlight>
Usage:
<langsyntaxhighlight ActionScriptlang="actionscript">import Node;
 
var A:Node = new Node(1);
Line 376:
var C:Node = new Node(3);
A.insert(B);
A.insert(C);</langsyntaxhighlight>
 
=={{header|Ada}}==
We must create a context clause making the predefined generic procedure Ada.Unchecked_Deallocation visible to this program.
<langsyntaxhighlight lang="ada">with Ada.Unchecked_Deallocation;
-- Define the link type
procedure Singly_Linked is
Line 413:
Free(B);
Free(C);
end Singly_Linked;</langsyntaxhighlight>
 
=={{header|ALGOL 68}}==
Line 419:
standard library. However Linked lists are presented in standard text
book examples. Or can be manually constructed, eg:
<langsyntaxhighlight lang="algol68">MODE STRINGLIST = STRUCT(STRING value, REF STRINGLIST next);
 
STRINGLIST list := ("Big",
Line 443:
node := next OF node
OD;
print((newline))</langsyntaxhighlight>
Output:<pre>Big fjords vex VERY quick waltz nymph </pre>
 
=={{header|ALGOL W}}==
<langsyntaxhighlight lang="algolw"> % inserts a new value after the specified element of a list %
procedure insert( reference(ListI) value list
; integer value newValue
Line 460:
 
% insert a new value into the list %
insert( next(head), 4077 );</langsyntaxhighlight>
 
=={{header|ARM Assembly}}==
{{works with|as|Raspberry Pi}}
<syntaxhighlight lang="arm assembly">
<lang ARM Assembly>
/* ARM assembly Raspberry PI */
/* program insertList.s */
Line 644:
bx lr @ leave function
iMagicNumber: .int 0xCCCCCCCD
</syntaxhighlight>
</lang>
 
=={{header|ATS}}==
Line 658:
that the insertion routine will terminate.
 
<langsyntaxhighlight ATSlang="ats">(*------------------------------------------------------------------*)
 
(* The Rosetta Code linear list type can contain any vt@ype.
Line 774:
 
implement
main0 () = ()</langsyntaxhighlight>
 
{{out}}
Line 783:
 
=={{header|AutoHotkey}}==
<syntaxhighlight lang="autohotkey">a = 1
<lang AutoHotkey>a = 1
a_next = b
b = 2
Line 799:
%old%_next := new
%new%_next := temp
}</langsyntaxhighlight>
 
=={{header|Axe}}==
<langsyntaxhighlight lang="axe">Lbl INSERT
{r₁+2}ʳ→{r₂+2}ʳ
r₂→{r₁+2}ʳ
r₁
Return</langsyntaxhighlight>
 
=={{header|BBC BASIC}}==
{{works with|BBC BASIC for Windows}}
<langsyntaxhighlight lang="bbcbasic"> DIM node{pNext%, iData%}
DIM a{} = node{}, b{} = node{}, c{} = node{}
Line 825:
here.pNext% = new{}
ENDPROC
</syntaxhighlight>
</lang>
 
=={{header|C}}==
Line 831:
Define the method:
 
<langsyntaxhighlight lang="c">void insert_append (struct link *anchor, struct link *newlink) {
newlink->next = anchor->next;
anchor->next = newlink;
}</langsyntaxhighlight>
 
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.
<langsyntaxhighlight lang="c">struct link *a, *b, *c;
a = malloc(sizeof(link));
b = malloc(sizeof(link));
Line 847:
a->data = 1;
b->data = 2;
c->data = 3;</langsyntaxhighlight>
 
Prepare our initial list
<syntaxhighlight lang ="c"> insert_append (a, b);</langsyntaxhighlight>
 
Insert element c after element a
<syntaxhighlight lang ="c"> insert_append (a, c);</langsyntaxhighlight>
 
Remember to free the memory once we're done.
<langsyntaxhighlight lang="c"> free (a);
free (b);
free (c);</langsyntaxhighlight>
 
=={{header|C sharp|C#}}==
Line 864:
 
Creates nodes and inserts them from the data passed.
<langsyntaxhighlight lang="csharp">static void InsertAfter<T>(LinkedListNode<T> prev, T value)
{
prev.Next = new Link() { Value = value, Next = prev.Next };
}</langsyntaxhighlight>
 
<langsyntaxhighlight lang="csharp">static void Main()
{
//Create A(5)->B(7)
Line 876:
//Insert C between A and B
InsertAfter(A, 15);
}</langsyntaxhighlight>
 
=={{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.
 
<langsyntaxhighlight lang="cpp">template<typename T> void insert_after(link<T>* list_node, link<T>* new_node)
{
new_node->next = list_node->next;
list_node->next = new_node;
};</langsyntaxhighlight>
 
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.
<langsyntaxhighlight lang="cpp">link<int>* a = new link<int>('A', new link<int>('B'));
link<int>* c = new link<int>('C');</langsyntaxhighlight>
 
Now insert c after a:
<syntaxhighlight lang ="cpp"> insert_after(a, c);</langsyntaxhighlight>
 
Finally destroy the list:
<langsyntaxhighlight lang="cpp">while (a)
{
link<int>* tmp = a;
a = a->next;
delete tmp;
}</langsyntaxhighlight>
 
=={{header|Clojure}}==
 
<langsyntaxhighlight lang="lisp">(defn insert-after [new old ls]
(cond (empty? ls) ls
(= (first ls) old) (cons old (cons new (rest ls)))
:else (cons (first ls) (insert-after new old (rest ls)))))</langsyntaxhighlight>
 
And the test:
<langsyntaxhighlight lang="lisp">user=> (insert-after 'c 'a '(a b))
(a c b)</langsyntaxhighlight>
 
=={{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.
 
<langsyntaxhighlight 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
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))))</langsyntaxhighlight>
 
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.
 
<langsyntaxhighlight lang="lisp">(defun simple-insert-after (new-element old-element list &key (test 'eql))
(let ((tail (rest (member old-element list :test test))))
(nconc (ldiff list tail)
(cons new-element tail))))</langsyntaxhighlight>
 
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.)
 
<langsyntaxhighlight lang="lisp">(defun insert-after (list new existing &key (test #'eql))
"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)))</langsyntaxhighlight>
 
=={{header|D}}==
<langsyntaxhighlight lang="d">struct SLinkedNode(T) {
T data;
typeof(this)* next;
Line 985:
 
// The GC will collect the memory.
}</langsyntaxhighlight>
 
=={{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 (* ... *).
 
<langsyntaxhighlight lang="delphi">// Using the same type defs from the one way list example.
 
Type
Line 1,048:
CurrentNode.Next := result ;
end;
end;</langsyntaxhighlight>
 
=={{header|E}}==
 
<langsyntaxhighlight lang="e">def insertAfter(head :LinkedList ? (!head.null()),
new :LinkedList ? (new.next().null())) {
new.setNext(head.next())
Line 1,069:
println(x.value())
x := x.next()
}</langsyntaxhighlight>
 
=={{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.
<langsyntaxhighlight lang="lisp">
(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>
</lang>
 
=={{header|Elena}}==
<langsyntaxhighlight lang="elena">singleton linkHelper
{
insertAfter(Link prev, IntNumber i)
Line 1,094:
prev.Next := new Link(i, prev.Next)
}
}</langsyntaxhighlight>
 
=={{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">
<lang Erlang>
-module( singly_linked_list ).
 
Line 1,150:
loop_foreach( _Fun, nonext ) -> ok;
loop_foreach( Fun, Next ) -> Next ! {foreach, Fun}.
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,160:
 
=={{header|Factor}}==
<langsyntaxhighlight lang="factor">: list-append ( previous new -- )
[ swap next>> >>next drop ] [ >>next drop ] 2bi ;
 
Line 1,168:
[ C <linked-list> list-append ] keep
[ B <linked-list> list-append ] keep
.</langsyntaxhighlight>
Output:
<pre>
Line 1,186:
Extending Node class from [[Singly-Linked_List_(element)]]:
 
<langsyntaxhighlight lang="fantom">
class Node
{
Line 1,221:
}
}
</syntaxhighlight>
</lang>
 
Output:
Line 1,233:
 
Using the linked list concept described in the [[Singly-Linked_List_(element)]] topic:
<langsyntaxhighlight lang="forth">\ Create the list and some list elements
create A 0 , char A ,
create B 0 , char B ,
create C 0 , char C ,</langsyntaxhighlight>
 
Now insert b after a and c after b, giving a->b->c
<langsyntaxhighlight lang="forth">B A chain
C B chain</langsyntaxhighlight>
 
Here is an abbreviated version of the definition of 'chain' from the other article:
<langsyntaxhighlight lang="forth"> : chain ( a b -- ) 2dup @ swap ! ! ;</langsyntaxhighlight>
 
=={{header|Fortran}}==
In ISO Fortran 95 or later:
<langsyntaxhighlight lang="fortran">elemental subroutine addAfter(nodeBefore,value)
type (node), intent(inout) :: nodeBefore
real, intent(in) :: value
Line 1,256:
newNode%next => nodeBefore%next
nodeBefore%next => newNode
end subroutine addAfter</langsyntaxhighlight>
 
=={{header|FreeBASIC}}==
Assumes you already have the ll_int data type, defined [[Singly-linked_list/Element_definition#FreeBASIC|here]].
<langsyntaxhighlight lang="freebasic">sub insert_ll_int( anchor as ll_int ptr, ins as ll_int ptr)
ins->nxt = anchor->nxt
anchor->nxt = ins
end sub</langsyntaxhighlight>
 
=={{header|Go}}==
<langsyntaxhighlight lang="go">package main
 
import "fmt"
Line 1,303:
h.insert("C")
h.printList()
}</langsyntaxhighlight>
Output:
<pre>
Line 1,312:
=={{header|Groovy}}==
Solution (uses ListNode from [[Singly-Linked List (element)#Groovy]]):
<langsyntaxhighlight lang="groovy">class NodeList {
private enum Flag { FRONT }
private ListNode head
Line 1,331:
}
String toString() { "${head}" }
}</langsyntaxhighlight>
 
Test:
<langsyntaxhighlight lang="groovy">def list = new NodeList()
list.insert('B')
list.insert('A')
Line 1,340:
 
list.insert('C', 'A')
println list</langsyntaxhighlight>
 
Output:
Line 1,348:
=={{header|Haskell}}==
This kind of list manipulation is [[unidiomatic]] Haskell. But you can try the following:
<langsyntaxhighlight lang="haskell">insertAfter a b (c:cs) | a==c = a : b : cs
| otherwise = c : insertAfter a b cs
insertAfter _ _ [] = error "Can't insert"</langsyntaxhighlight>
 
==Icon and Unicon==
Line 1,358:
==={{header|Icon}}===
 
<syntaxhighlight lang="icon">
<lang Icon>
record Node (value, successor)
 
Line 1,365:
node.successor := newNode
end
</syntaxhighlight>
</lang>
 
==={{header|Unicon}}===
 
<syntaxhighlight lang="unicon">
<lang Unicon>
class Node (value, successor)
 
Line 1,381:
self.successor := successor
end
</syntaxhighlight>
</lang>
 
=={{header|J}}==
 
<langsyntaxhighlight Jlang="j">list=: 1 65,:_ 66
A=:0 NB. reference into list
B=:1 NB. reference into list
Line 1,395:
localNewNode=: (localOldLinkRef { localListValue), localNewValue
(localListName)=: (localNewLinkRef localOldLinkRef} localListValue), localNewNode
)</langsyntaxhighlight>
 
With these definitions:
Line 1,407:
=={{header|Java}}==
Extending [[Singly-Linked_List_(element)#Java]]
<langsyntaxhighlight Javalang="java">void insertNode(Node<T> anchor_node, Node<T> new_node)
{
new_node.next = anchor_node.next;
anchor_node.next = new_node;
}</langsyntaxhighlight>
{{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]]
<langsyntaxhighlight lang="javascript">LinkedList.prototype.insertAfter = function(searchValue, nodeToInsert) {
if (this._value == searchValue) {
nodeToInsert.next(this.next());
Line 1,428:
}
var list = createLinkedListFromArray(['A','B']);
list.insertAfter('A', new LinkedList('C', null));</langsyntaxhighlight>
 
=={{header|jq}}==
Line 1,437:
see [[Singly-linked_list/Element_definition#jq]].
 
<langsyntaxhighlight lang="jq"> def new($item; $next):
if $next | (.==null or is_singly_linked_list)
then {$item, $next}
Line 1,447:
 
def insert($x):
if is_empty_singly_linked_list then {item: $x, next: null}
.next |= new($x; .);</lang>
else .next |= new($x; .)
end;</syntaxhighlight>
'''An example''':
<syntaxhighlight lang="jq">
<lang jq>
new(1) | insert(2)
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,467 ⟶ 1,469:
See the <tt>LinkedList</tt> implemented at [[Singly-linked_list/Element_definition#Julia]].
 
<langsyntaxhighlight lang="julia">function Base.insert!(ll::LinkedList{T}, index::Integer, item::T) where T
if index == 1
if isempty(ll)
Line 1,487 ⟶ 1,489:
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,516 ⟶ 1,518:
insertAfter(a, c)
println("After insertion : $a")
}</langsyntaxhighlight>
 
{{out}}
Line 1,525 ⟶ 1,527:
 
=={{header|Logo}}==
<langsyntaxhighlight lang="logo">to insert :after :list :value
localmake "tail member :after :list
if not empty? :tail [.setbf :tail fput :value bf :tail]
Line 1,531 ⟶ 1,533:
end
 
show insert 5 [3 5 1 8] 2</langsyntaxhighlight>
[3 5 2 1 8]
 
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<langsyntaxhighlight Mathematicalang="mathematica">Append[{a, b}, c]
->{a, b, c}</langsyntaxhighlight>
 
Node = {"item": null, "next": null}
Node.init = function(item)
node = new Node
node.item = item
return node
end function
 
=={{header|MiniScript}}==
We're choosing here to use the built-in list type, rather than make our own from scratch, since this is more representative of how one is likely to actually use MiniScript.
<syntaxhighlight lang="miniscript">
> myList = [100, 101, 102]
> myList.push 103
[100, 101, 102, 103]
> myList.insert 0, 99
[99, 100, 101, 102, 103]
> myList.insert 3,101.5
[99, 100, 101, 101.5, 102, 103]
</syntaxhighlight>
 
=={{header|Modula-3}}==
<langsyntaxhighlight lang="modula3">MODULE SinglyLinkedList EXPORTS Main;
 
TYPE
Line 1,564 ⟶ 1,585:
InsertAppend(a, b);
InsertAppend(a, c)
END SinglyLinkedList.</langsyntaxhighlight>
 
=={{header|Nim}}==
<langsyntaxhighlight lang="nim">type Node[T] = ref object
next: Node[T]
data: T
Line 1,583 ⟶ 1,604:
 
a.insertAppend(b)
b.insertAppend(c)</langsyntaxhighlight>
 
=={{header|OCaml}}==
This kind of list manipulation is unidiomatic OCaml. But you can try the following:
<langsyntaxhighlight lang="ocaml">let rec insert_after a b = function
c :: cs when a = c -> a :: b :: cs
| c :: cs -> c :: insert_after a b cs
| [] -> raise Not_found</langsyntaxhighlight>
 
=={{header|Odin}}==
<syntaxhighlight lang="odin">package main
 
Node :: struct {
data: rune,
next: ^Node,
}
 
insert_after :: proc(node, new_node: ^Node) {
new_node.next = node.next
node.next = new_node
}
 
main :: proc() {
a := new(Node)
a.data = 'A'
 
b := new(Node)
b.data = 'B'
 
c := new(Node)
c.data = 'C'
 
insert_after(a, b) // A -> B
insert_after(a, c) // A -> C -> B
 
assert(a.data == 'A')
assert(a.next.data == 'C')
assert(a.next.next.data == 'B')
}</syntaxhighlight>
 
=={{header|Oforth}}==
Line 1,596 ⟶ 1,648:
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).
 
<langsyntaxhighlight Oforthlang="oforth">Collection Class new: LinkedList(data, mutable next)
 
LinkedList method: initialize := next := data ;
Line 1,611 ⟶ 1,663:
: testLink LinkedList new($A, null) dup add($B) dup add($C) ;
 
testLink println</langsyntaxhighlight>
 
{{out}}
Line 1,620 ⟶ 1,672:
=={{header|ooRexx}}==
See [[Singly-linked_list/Element_definition#ooRexx|Single-linked list/Element definition]] for full class definition.
<syntaxhighlight lang="oorexx">
<lang ooRexx>
list = .linkedlistlist~new
index = list~insert("abc") -- insert a first item, keeping the index
Call show
list~insert("def") -- adds to the end
Call show
list~insert("123", .nil) -- adds to the begining
Call show
list~insert("456", index) -- inserts between "abc" and "def"
Call show
list~remove(index) -- removes "abc"
Call show
</lang>
exit
show:
s=''
Do x over list
s=s x
end
say s
Return</syntaxhighlight>
{{out]]
<pre> abc
abc def
123 abc def
123 abc 456 def
123 456 def
</pre>
 
=={{header|Pascal}}==
Line 1,634 ⟶ 1,705:
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.
 
<langsyntaxhighlight lang="pascal">type
pCharNode = ^CharNode;
CharNode = record
Line 1,648 ⟶ 1,719:
newnode^.next := listnode^.next;
listnode^.next := newnode;
end;</langsyntaxhighlight>
Usage example:
<langsyntaxhighlight lang="pascal">var
A, B: pCharNode;
begin
Line 1,676 ⟶ 1,747:
dispose(B);
end
end.</langsyntaxhighlight>
 
=={{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.
<langsyntaxhighlight lang="perl">my @l = ($A, $B);
push @l, $C, splice @l, 1;</langsyntaxhighlight>
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.
<langsyntaxhighlight lang="perl">sub insert_after {
# first argument: node to insert after
# second argument: node to insert
Line 1,701 ⟶ 1,772:
data => 2,
);
insert_after \%A, \%C;</langsyntaxhighlight>
Note that you don't have to name your new nodes. The following works just as well:
<langsyntaxhighlight lang="perl"> insert_after \%A, { data => 2 };</langsyntaxhighlight>
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:
<langsyntaxhighlight lang="perl">sub insert_after {
my $node = $_[0];
my $next = $node->{next};
Line 1,717 ⟶ 1,788:
}
$node->{next} = $next;
}</langsyntaxhighlight>
With this, it's rather easy to build a list:
<langsyntaxhighlight lang="perl">my %list = ( data => 'A' );
insert_after \%list, { data => 'B' }, { data => 'C' };</langsyntaxhighlight>
List handling is simplified if the variables themselves contain references. For example:
<langsyntaxhighlight lang="perl">my $list2;
 
# create a new list ('A'. 'B', 'C') and store it in $list2
Line 1,731 ⟶ 1,802:
 
# append new nodes ('A2a', 'A2b') after the second element (which now is 'A2')
insert_after $list2->{next}, { data => 'A2a' }, { data => 'A2b' };</langsyntaxhighlight>
 
=={{header|Phix}}==
See also [[Singly-linked_list/Traversal#Phix|Traversal]] and [[Singly-linked_list/Element_removal#Phix|Removal]].
<!--<syntaxhighlight lang="phix">(phixonline)-->
<lang Phix>enum NEXT,DATA
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
constant empty_sll = {{1}}
<span style="color: #008080;">enum</span> <span style="color: #000000;">NEXT</span><span style="color: #0000FF;">,</span><span style="color: #000000;">DATA</span>
sequence sll = empty_sll
<span style="color: #008080;">constant</span> <span style="color: #000000;">empty_sll</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{{</span><span style="color: #000000;">1</span><span style="color: #0000FF;">}}</span>
 
<span style="color: #004080;">sequence</span> <span style="color: #000000;">sll</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">deep_copy</span><span style="color: #0000FF;">(</span><span style="color: #000000;">empty_sll</span><span style="color: #0000FF;">)</span>
procedure insert_after(object data, integer pos=length(sll))
sll = append(sll,{sll[pos][NEXT],data})
<span style="color: #008080;">procedure</span> <span style="color: #000000;">insert_after</span><span style="color: #0000FF;">(</span><span style="color: #004080;">object</span> <span style="color: #000000;">data</span><span style="color: #0000FF;">,</span> <span style="color: #004080;">integer</span> <span style="color: #000000;">pos</span><span style="color: #0000FF;">=</span><span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">sll</span><span style="color: #0000FF;">))</span>
sll[pos][NEXT] = length(sll)
<span style="color: #000000;">sll</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">append</span><span style="color: #0000FF;">(</span><span style="color: #000000;">sll</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">sll</span><span style="color: #0000FF;">[</span><span style="color: #000000;">pos</span><span style="color: #0000FF;">][</span><span style="color: #000000;">NEXT</span><span style="color: #0000FF;">],</span><span style="color: #000000;">data</span><span style="color: #0000FF;">})</span>
end procedure
<span style="color: #000000;">sll</span><span style="color: #0000FF;">[</span><span style="color: #000000;">pos</span><span style="color: #0000FF;">][</span><span style="color: #000000;">NEXT</span><span style="color: #0000FF;">]</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">sll</span><span style="color: #0000FF;">)</span>
 
<span style="color: #008080;">end</span> <span style="color: #008080;">procedure</span>
insert_after("ONE")
insert_after("TWO")
<span style="color: #000000;">insert_after</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"ONE"</span><span style="color: #0000FF;">)</span>
insert_after("THREE")
<span style="color: #000000;">insert_after</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"TWO"</span><span style="color: #0000FF;">)</span>
 
<span style="color: #000000;">insert_after</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"THREE"</span><span style="color: #0000FF;">)</span>
?sll</lang>
<span style="color: #0000FF;">?</span><span style="color: #000000;">sll</span>
<!--</syntaxhighlight>-->
{{out}}
<pre>
Line 1,756 ⟶ 1,830:
=={{header|PicoLisp}}==
Destructive operation
<langsyntaxhighlight PicoLisplang="picolisp">(de insertAfter (Item Lst New)
(when (member Item Lst)
(con @ (cons New (cdr @))) )
Lst )</langsyntaxhighlight>
Non-destructive operation
<langsyntaxhighlight PicoLisplang="picolisp">(de insertAfter (Item Lst New)
(if (index Item Lst)
(conc (cut @ 'Lst) (cons New Lst))
Lst ) )</langsyntaxhighlight>
Output in both cases:
<pre>: (insertAfter 'A '(A B) 'C)
Line 1,773 ⟶ 1,847:
 
=={{header|PL/I}}==
<syntaxhighlight lang="pl/i">
<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,781 ⟶ 1,855:
node.value = V;
H->p = Q; /* Break the list at H, and point it at the new node. */
</syntaxhighlight>
</lang>
 
=={{header|Pop11}}==
Line 1,787 ⟶ 1,861:
In Pop11 one normally uses built-in lists:
 
<langsyntaxhighlight lang="pop11">define insert_into_list(anchor, x);
cons(x, back(anchor)) -> back(anchor);
enddefine;
Line 1,794 ⟶ 1,868:
insert_into_list(l1, "b");
;;; insert c
insert_into_list(l1, "c");</langsyntaxhighlight>
 
If one wants one can use user-defined list node (for convenience we repeat definition of list node):
 
<langsyntaxhighlight lang="pop11">uses objectclass;
define :class ListNode;
slot value = [];
Line 1,811 ⟶ 1,885:
insert_into_List(l2, "b");
;;; insert c
insert_into_List(l2, "c");</langsyntaxhighlight>
 
Note that user-defined case differs from built-in case only because of names.
 
=={{header|PureBasic}}==
<langsyntaxhighlight PureBasiclang="purebasic">Procedure insertAfter(Value, *node.MyData = #Null)
Protected *newNode.MyData = AllocateMemory(SizeOf(MyData))
If *newNode
Line 1,833 ⟶ 1,907:
*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</langsyntaxhighlight>
 
=={{header|Python}}==
<langsyntaxhighlight lang="python">def chain_insert(lst, at, item):
while lst is not None:
if lst[0] == at:
Line 1,847 ⟶ 1,921:
chain = ['A', ['B', None]]
chain_insert(chain, 'A', 'C')
print chain</langsyntaxhighlight>
Output:
<langsyntaxhighlight lang="python">['A', ['C', ['B', None]]]</langsyntaxhighlight>
 
=={{header|Racket}}==
 
<syntaxhighlight lang="racket">
<lang Racket>
#lang racket
 
Line 1,865 ⟶ 1,939:
(insert-after! l 2 2.5)
l ; -> (mcons 1 (mcons 2 (mcons 2.5 (mcons 3))))
</syntaxhighlight>
</lang>
 
=={{header|Raku}}==
Line 1,872 ⟶ 1,946:
Extending <tt>class Cell</tt> from [[Singly-linked_list/Element_definition#Raku]]:
 
<syntaxhighlight lang="raku" perl6line> method insert ($value) {
$.next = Cell.new(:$value, :$.next)
}</langsyntaxhighlight>
 
=={{header|REXX}}==
<langsyntaxhighlight lang="rexx">/*REXX program demonstrates how to create and show a single-linked list. */
@.=0/* and how to insert an element /*define a null linked list. */
call set@ 3z.=0 /*linked list:define a 12null Prothlinked primesz. */
Call set_list 3 /* linked list: 12 Proth primes */
call set@ 5
Call set_list 5 /*see https://mathworld.wolfram.com/ProthPrime.html*/
call set@ 13
Call set_list 13
call set@ 17
Call set_list 17
call set@ 41
Call set_list 41
call set@ 97
Call set_list 97
call set@ 113
Call set_list 113
call set@ 193
Call set_list 193
call set@ 241
Call set_list 241
call set@ 257
Call set_list 257
call set@ 353
Call set_list 353
call set@ 449
Call set_list 449
call list@
Call show_list
after = 97 /* ◄──── REXX code to do insert. */
newValnewval=100 /* ◄──── Insert this "value " " " " */
#after=@..after 97 /* ◄──── " " " " after the "element with this value */
nnn=z..after call ins@ #,newVal /* ◄──── " "position of z´this "value " " */
Call ins_list nnn,newval /* perform the insertion */
say
Say ''
say 'a new value of' newval "has been inserted after element value:" after
Say 'a new value of' newval 'has been inserted',
call list@
exit 'after element having the /*stick a fork in it, wevalue:'re done.*/after
Call show_list
/*──────────────────────────────────INS@ subroutine─────────────────────*/
Exit /* stick a fork in it, we're done.*/
ins@: procedure expose @.; parse arg #,y
 
@._last=@._last+1 /*bump number of list elements. */
set_list: Procedure Expose z.
_=@._last
@._._value=y Parse Arg value /* get element /*defineto newbe valueadded to list element. */
last=z.0 /* set the previous last element. */
@._._next=@.#._next
new=z.0+1 /* set the new ast element. */
@.#._next=_
@. z.y0=_ new /*set adefine locatornext pointeritem toin self.linked list*/
@ z.max_width=max(@last.max_width,length(y))0next=new /* set maximumthe width ofnext any pointer value. */
return z.new.0value=value /*return toset invokeritem ofto thisthe sub.value specified*/
z.new.0next=0 /* set the next pointer value. */
/*──────────────────────────────────LIST@ subroutine────────────────────*/
z..value=new /* set a locator pointer to self. */
list@: say; w=max(7, @.max_width ) /*use the max width of nums or 7.*/
z.0width=max(z.0width,length(value)) /*set maximum width of any value*/
say center('item',6) center('value',w) center('next',6)
Return
say center('' ,6,'─') center('' ,w,'─') center('' ,6,'─')
 
p=1
ins_list: Procedure Expose z.
do j=1 until p==0 /*show all entries of linked list*/
Parse Arg nnn,value
say right(j,6) right(@.p._value,w) right(@.p._next,6)
z.0=z.0+1 /* bump number of list elements. */
p=@.p._next
last=z.0 /* position of the new value */
end /*j*/
z.last.0value=value /* store the new value */
return
z.last.0next=z.nnn.0next /* uptate the pointers to the */
/*──────────────────────────────────SET@ subroutine─────────────────────*/
set@: procedure expose @z.;nnn.0next=last parse arg y /*get next element to be added to list */
_=@._last z..value=last /* store position /*setof the previous last element.new value*/
z.0width=max(z.0width,length(value)) /*set maximum width of any value*/
n=_+1 /*bump last ptr in linked list. */
Return
@._._next=n /*set the next pointer value. */
 
@._last=n /*define next item in linked list*/
show_list:
@.n._value=y /*set item to the value specified*/
Say
@.n._next=0 /*set the next pointer value. */
@..y=n w=max(7,z.0width) /* use the max width of nums or /*set a locator pointer to self7. */
Say center('item',6) 'position' center('value',w) center('next',6)
@.max_width=max(@.max_width,length(y)) /*set maximum width of any value.*/
Say center('',6,'-') '--------' center('',w,'-') center('',6,'-')
return /*return to invoker of this sub. */</lang>
p=1
Do j=1 Until p==0 /* show all entries of linked list*/
Say right(j,6) right(p,8) right(z.p.0value,w) right(z.p.0next,6)
p=z.p.0next
End /* j */
Return</syntaxhighlight>
'''output'''
<pre>
item position value next
------ -------- ------- ------
────── ─────── ──────
1 1 3 2
2 2 5 3
3 3 13 4
4 4 17 5
5 5 41 6
6 6 97 7
7 7 113 8
8 8 193 9
9 9 241 10
10 10 257 11
11 11 353 12
12 12 449 0
 
a new value of 100 has been inserted after element having the value: 97
 
item position value next
------ -------- ------- ------
────── ─────── ──────
1 1 3 2
2 2 5 3
3 3 13 4
4 4 17 5
5 5 41 6
6 6 97 13
7 13 100 7
8 7 113 8
9 8 193 9
10 9 241 10
11 10 257 11
12 11 353 12
13 12 449 0</pre>
</pre>
 
=={{header|Ruby}}==
<langsyntaxhighlight lang="ruby">class ListNode
def insert_after(search_value, new_value)
if search_value == value
Line 1,981 ⟶ 2,060:
 
list = ListNode.new(:a, ListNode.new(:b))
list.insert_after(:a, :c)</langsyntaxhighlight>
 
=={{header|Rust}}==
 
Extending [[Singly-Linked List (element)#Rust]]. Please see that page for the Linked List struct declarations.
<langsyntaxhighlight lang="rust">impl<T> List<T> {
pub fn new() -> Self {
List { head: None }
Line 1,997 ⟶ 2,076:
});
self.head = Some(new_node);
}</langsyntaxhighlight>
 
=={{header|Scala}}==
In Scala (and functional programming) we create a new list instead of modifying existing one.
<langsyntaxhighlight lang="scala">
/*
Here is a basic list definition
Line 2,013 ⟶ 2,092:
def add[A](as: List[A], a: A): List[A] = Cons(a, as)
}
</syntaxhighlight>
</lang>
 
=={{header|Scheme}}==
Non-mutating:
<langsyntaxhighlight lang="scheme">(define (insert-after a b lst)
(if (null? lst)
lst ; This should be an error, but we will just return the list untouched
Line 2,024 ⟶ 2,103:
(if (equal? a c)
(cons a (cons b cs))
(cons c (insert-after a b cs))))))</langsyntaxhighlight>
 
Mutating:
<langsyntaxhighlight lang="scheme">(define (insert-after! a b lst)
(let ((pos (member a lst)))
(if pos
(set-cdr! pos (cons b (cdr pos))))))</langsyntaxhighlight>
 
=={{header|Sidef}}==
<langsyntaxhighlight lang="ruby">func insert_after(a,b) {
b{:next} = a{:next};
a{:next} = b;
Line 2,050 ⟶ 2,129:
);
 
insert_after(A, C);</langsyntaxhighlight>
 
=={{header|Stata}}==
Line 2,064 ⟶ 2,143:
No error checking is included.
 
<langsyntaxhighlight lang="tcl">
proc insertIntoList {existingList predecessor newElement} {
upvar $existingList exList
Line 2,073 ⟶ 2,152:
insertIntoList list A C
puts $list
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 2,081 ⟶ 2,160:
=={{header|Wren}}==
{{libheader|Wren-llist}}
<langsyntaxhighlight ecmascriptlang="wren">import "./llist" for LinkedList
 
var ll = LinkedList.new(["A", "B"])
ll.insertAfter("A", "C")
System.print(ll)</langsyntaxhighlight>
 
{{out}}
Line 2,093 ⟶ 2,172:
 
=={{header|X86 Assembly}}==
<langsyntaxhighlight lang="x86asm">
; x86_64 Linux NASM
; Linked_List_Insert.asm
Line 2,123 ⟶ 2,202:
 
%endif
</syntaxhighlight>
</lang>
 
=={{header|XPL0}}==
<langsyntaxhighlight XPL0lang="xpl0">def \Node\ Link, Data; \linked list element definition
def IntSize = 4; \number of bytes in an integer
 
Line 2,153 ⟶ 2,232:
MyNode:= MyNode(Link); \move to next node
];
]</langsyntaxhighlight>
 
{{out}}
Line 2,161 ⟶ 2,240:
 
=={{header|Yabasic}}==
<langsyntaxhighlight Yabasiclang="yabasic">// Rosetta Code problem: http://rosettacode.org/wiki/Singly-linked_list/Element_insertion
// by Galileo, 02/2022
 
Line 2,221 ⟶ 2,300:
printNode(1)
printNode(2)
printNode(3)</langsyntaxhighlight>{{out}}
<pre>1000
3000
Line 2,229 ⟶ 2,308:
=={{header|zkl}}==
In place:
<langsyntaxhighlight 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")</langsyntaxhighlight>
Create a new list:
<langsyntaxhighlight lang="zkl">a:=ROList("a","b","c");
n:=a.index("b"); a[0,n].append("foo").extend(a[n,*]) //-->ROList("a","foo","b","c")</langsyntaxhighlight>
 
=={{header|Zig}}==
<syntaxhighlight lang="zig">
const std = @import("std");
 
var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
 
const allocator = arena.allocator();
 
pub fn LinkedList(comptime Value: type) type {
return struct {
const This = @This();
 
const Node = struct {
value: Value,
next: ?*Node,
};
 
head: ?*Node,
tail: ?*Node,
 
pub fn init() This {
return LinkedList(Value) {
.head = null,
.tail = null,
};
}
 
pub fn add(this: *This, value: Value) !void {
var newNode = try allocator.create(Node);
 
newNode.* = .{ .value = value, .next = null };
 
if (this.tail) |tail| {
tail.next = newNode;
this.tail = newNode;
} else if (this.head) |head| {
head.next = newNode;
this.tail = newNode;
} else {
this.head = newNode;
}
}
};
}
</syntaxhighlight>
 
Create a new list:
 
<syntaxhighlight lang="zig">
var l1 = LinkedList(i32).init();
</syntaxhighlight>
 
Add element:
 
<syntaxhighlight lang="zig">
try list.add(1);
</syntaxhighlight>
9,476

edits