Logo

Programming-Idioms

  • C#
  • Java
  • PHP
  • Lisp

Idiom #44 Insert element in list

Insert the element x at position i in the list s. Further elements must be shifted to the right.

Inserting the element x at a given position in the list s
(defun ins (lst x i)
 (if (zerop i) (cons x lst)
     (cons (car lst) (ins (cdr lst) x (- i 1)))))

(setf s (ins s x i))
using System.Collections.Generic;
s.Insert(i, x);
import java.util.List;
s.add(i, x);
import static java.lang.System.arraycopy;
int a = 0, n = s.length,
    t[] = new int[n + 1];
arraycopy(s, a, t, a, i);
t[i] = x;
arraycopy(s, i, t, i + 1, n - i);
import static java.lang.System.arraycopy;
import static java.lang.reflect.Array.newInstance;
int a = 0, n = s.length;
Class<?> c = s.getClass().getComponentType();
T t[] = (T[]) newInstance(c, n + 1);
arraycopy(s, a, t, a, i);
t[i] = x;
arraycopy(s, i, t, i + 1, n - i);
array_splice($s, $i, 0, $x);
s.insert (s.begin () + i, x);

New implementation...