cse1301 computer programming: lecture 33 linked lists
Post on 19-Dec-2015
226 views
TRANSCRIPT
Recall: Sorted List
0 1 2 3 4
Ann Dave HumphryBen
Q: Is there an alternative way to implement a sorted list?
A: Linked List
Linked List
• Uses an array to form a sorted list
• Each element has a link to the next item
8 2 9 5 34
first 10 1 2 3 54
5 34 02 -1
List Element
struct ListElementRec
{
int item;
int next;
};
typedef struct ListElementRec ListElement;
2item
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 fieldconst 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 4
8 2 9 5 34
first 10 1 2 3 54
5 34 02 END
Searching in a linked list
• See Algorithm in Lecture Notes
• Example: Trace values for:index
linkedList[index].item
linkedList[index].next