CSE1301 Computer Programming: Lecture 33 Linked Lists
Topics Linked list List element Searching a linked list
Recall: Sorted List 01234
01234 Ann
Recall: Sorted List Ann
Recall: Sorted List Ann Dave
Recall: Sorted List Ann Dave
Recall: Sorted List Ann Dave Humphry
Recall: Sorted List Ann Dave Humphry
Recall: Sorted List Ann Dave Humphry Ben
Recall: Sorted List Ann Dave Humphry Ben
Recall: Sorted List Ann Dave Humphry Ben
Recall: Sorted List Ann Dave Humphry Ben
Recall: Sorted List Ann Dave Humphry Ben Q: Is there an alternative way to implement a sorted list? A: Linked List
01234 Ann Dave Humphry Ben First
01234 Ann Dave Humphry Ben First
01234 Ann Dave Humphry Ben First
01234 Ann Dave Humphry Ben First
01234 Ann Dave Humphry First Ben
01234 Ann Dave Humphry Ben First
01234 Ann Dave Humphry Ben First
01234 Ann Dave Humphry Ben First Amy
01234 Ann Dave Humphry Ben First Amy
01234 Ann Dave Humphry Ben First Amy
01234 Ann Dave Humphry Ben First Amy
01234 first element index of next element item invalid index (eg. -1)
Linked List Uses an array to form a sorted list Each element has a link to the next item first
List Element struct ListElementRec { int item; int next; }; typedef struct ListElementRec ListElement; 2 item next 5
What will a program have? An array of these structs ListElement list[maxListLength]; A variable to store the position of the first element of the list int first; The last element in the list must contain a non valid integer in its next field const int END = -1;
Accessing list items First element (a struct) list[first]; First item in list list[first].item; Index of next element list[first].next;
Accessing list items Next item in list int index; list[list[index].next].item; index first END
Searching in a linked list See Algorithm in Lecture Notes Example: Trace values for: index linkedList[index].item linkedList[index].next
Summary In a linked list, list elements don't have to be ordered in the array itself. A second field in the list element structure, "next", maintains the list ordering. Next lecture: adding and deleting from a linked list