Why does concatenation of lists take O (n)?

According to the theory of ADT (Algebraic Data Types), the concatenation of two lists should take O(n), where nis the length of the first list. You basically have to recursively go through the first list until you find the end.

From another point of view, it can be argued that the second list can simply be associated with the last element of the first. This will take a constant time if the end of the first list is known.

What am I missing here?

+4
source share
4 answers

- . - + , , Tuple, :

let tupleList = ("a", ("b", ("c", [])))

"" "head". O (1), fst:

> fst tupleList

, :

let tupleList2 = ("x",snd tupleList)

O (1). ? . - : tupleList tupleList2. tupleList2, . , , - .

3- :

> snd . snd $ fst tupleList

O (3), , .. O (n).

O (1)? , . O (1) , , .

(ASIDE: , Linked List Array, , Big-O , get, , , , ..).

, , . concat tupleList ("e", ("f", [])). , :

tupleList3 = (fst tupleList, (snd $ fst tupleList, (snd . snd $ fst tupleList, ("e", ("f", [])))

, O (n), . : , .

, , , ? , O (1). , . ?

, :

data Queue a = Queue { last :: Queue a, head :: a, next :: Queue a} | Empty
appendEnd :: a -> Queue a -> Queue a
appendEnd a2 (Queue l, h, n) = ????

"", , . . , , .

, , , . O (n).

, :

List a []

, . . .

List a (List a [])

, . . . , . . , O (1).

Haskell Doubly Linked Lists. "" (, , FIFO) . Haskell .

, , , Purely Funtional Data Structures.

EDIT: - : http://visualgo.net/list.html, , " " O ( 1). , . , . , .

+2

Haskell (). , tail ( ), consing x : , . , , , .

++ [x], , , , . ,

x = [1..5]
n = length (x ++ [6]) + length x

x x++[6], n 12, . x 5, n 11.

, , , x , ( "" ). , , x++[6] , x , x.

@Ben, " " . , ( "" ), . ,

x = [[1,2],[2,3]]
y = x ++ [[3,4]]

[1,2],[2,3],[3,4] . x,y , .

+4

, , , TCS Stackexchange : , , .

90- ; . , Haskell.

+4
source

To connect the two lists (name them xsand ys), we need to change the final node in xsto associate it with the (first) node ys.

But Haskell lists are immutable, so you need to create a copy first xs. This operation O(n)(where nis the length xs).

Example:

xs
|
v
1 -> 2 -> 3

1 -> 2 -> 3 -> 4 -> 5 -> 6 -> 7
^              ^
|              |
xs ++ ys       ys
0
source

All Articles