Definition. Linked Lists

[comp1110-2S]

A linked list is a way to store a sequence of items, one after another, where each item points to the next. Unlike arrays, it is not necessary to know ahead of time how many items the list will contain. It is a very common example of a recursive data type, where a type occurs as a field of itself. Here, we describe a linked list of integers by defining a recursive class type:

// An IntList is either // null - representing the empty list // an IntList object, representing a part of a non-empty list class IntList { int value; IntList rest; IntList(int v, IntList r) { value = v; rest = r; } }

Here value is the first integer in the list, rest is the rest of the list (or null if there are no more integers). Therefore, null plays the role of the base case of our recursion, while an IntList object (which contains another IntList) is the recursive case.

// Start with an empty list IntList list = null; // Add 3 first list = new IntList(3, list); // Add 2 in front of 3 list = new IntList(2, list); // Add 1 in front of 2 list = new IntList(1, list);
bars magnifying-glass caret-down plus minus arrow-right xmark