Abstract Data Type
Abstract Data Type
• Stacks • Heaps
• Queues • Graphs
• Arrays
LIST ADT
• We will deal with a general list of the form a1, a2, a3, . .
. , an. We say that the size of this list is n. We will call the
special list of size 0 a null list.
• For any list except the null list, we say that ai+l follows
(or succeeds) ai (i < n) and that ai-1 precedes ai (i > 1).
• The first element of the list is a1, and the last element is
an.
The List ADT: Operations
Popular choices:
• –insert(x, k) (add element at kth position)
• –delete(k) (delete elem. at kth position)
• –findKth (find element at position k)
• –find(x) (find position of element)
• –next (find element after a specified element)
• –previous (find element before a specified element)
• –printList (display list)
• –makeEmpty (get rid of contents)
LIST ADT Implementations
Item to be
tmp X inserted
A B C
curr
X
tmp=(node *) malloc(sizeof(node));
tmp->next=curr->next;
curr->next=tmp;
}
Spring 2012 Programming and Data Structure 26
Function to test whether a linked list is
empty
int
Is_empty( LIST L )
{
return( L->next == NULL );
} Empty list with
header
Function to test whether current position is
the last in a linked list
int
}
Find routine
/* Return position of x in L; NULL if not found */
position
find ( element_type x, LIST L )
{
position p;
/*1*/ p = L->next;
/*2*/ while( (p != NULL) && (p->element != x) )
/*3*/ p = p->next;
/*4*/ return p;
}
Find routine
• Find, shown in above Figure, returns the
position in the list of some element.
• Line 2 takes advantage of the fact that the
and (&&) operation is short-circuited: if the
first half of the and is false, the result is
automatically false and the second half is not
executed.
Deletion routine for Linked Lists
• Our fourth routine will delete some element x in list L. We
need to decide what to do if x occurs more than once or not at
all.
• Our routine deletes the first occurrence of x and does nothing
if x is not in the list.
• To do this, we find p, which is the cell prior to the one
containing x, via a call to find_previous.
• The code to implement this is shown in following Figure . The
find_previous routine is similar to find and is shown in next
Figure.
Illustration: Deletion
Item to be deleted
A B C
tmp
curr
A B C