Singly-linked list/Element definition: Difference between revisions

m
Line 1,380:
return(x)
}
}</lang>
 
=== Remove and return nth element ===
 
<lang stata>transmorphic scalar list_remove(struct list scalar a,
real scalar n) {
pointer(struct item scalar) scalar p, q
real scalar i
transmorphic scalar x
p = a.head
if (n == 1) {
if (p == NULL) {
_error("empty list")
}
x = (*p).value
if (p == a.tail) {
a.head = a.tail = NULL
} else {
a.head = (*p).next
}
} else {
for (i = 2; p != NULL & i < n; i++) {
p = (*p).next
}
if (p == NULL) {
_error("too few elements in list")
}
q = (*p).next
if (q == NULL) {
_error("too few elements in list")
}
x = (*q).value
if (q == a.tail) {
a.tail = p
}
(*p).next = (*q).next
}
return(x)
}</lang>
 
1,336

edits