![]() |
CS111 IntList Contract |
The IntList
class describes immutable linked lists of
integers. An integer list is defined recursively as either
Integer lists are immutable in the
sense that the head or tail of a list node cannot be changed after
the list node has been created (via the prepend()
method).
Constructor Methods
public IntList ()
Constructs an empty integer list.
public IntList (int n, IntList L)
Constructs a new integer list node whose head is n
and
whose tail is L
.
Class Methods
public static IntList empty()
Returns an empty integer list.
IntList.empty()
behaves like new IntList()
.
public static IntList prepend (int n, IntList L)
Returns a new integer list node whose head is n
and
whose tail is L
.
IntList.prepend(n,L)
is equivalent to new IntList(n, L)
.
public static boolean isEmpty (IntList L)
Returns true
if L
is an empty integer list node
and false
if L
is a nonempty integer list node.
public static int head (IntList L)
Returns the integer that is the head component of the integer list node
L
. Signals an exception if L
is empty.
public static IntList tail (IntList L)
Returns the integer list that is the tail component of the integer list
node L
. Signals an exception if L
is empty.
public static boolean equals (IntList L1, IntList L2)
Returns true
if L1
and L2
have the same length and the same elements
in the same order; otherwise returns false
. Note that the equals
method behaves differently than ==
on lists, which determines if
two list nodes were created by the same call to prepend
. For instance,
if L
is the list [1,2,3]
, then
L.equals(prepend(1,tail(L)))
is true
,
but L == prepend(1,tail(L))
is false
.
public static String toString (IntList L)
Returns a string representation of of the integer list L
in which the integer list elements are separated by commas
and delimited by square brackets.
For example, if L1
is a list containing the sequence of
integers 6, -17 and 42, then toString(L1)
returns "[6,-17,42]"
.
public static IntList fromString (String s)
If s
is the printed representation of an integer list
(i.e., comma separated integers delimited by square brackets),
returns an IntList
with that representation.
For example, fromString("[7,-2,4]")
returns
an 3-element integer list with elements 7
,
-2
, and 4
.
If s
is not the printed representation of an integer list,
signals an error.