This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
CSE1301 Computer Programming:
Lecture 33Linked Lists
Topics
• Linked list
• List element
• Searching a linked list
Recall: Sorted List
0 1 2 3 4
Recall: Sorted List
0 1 2 3 4
Ann
Recall: Sorted List
0 1 2 3 4
Ann
Recall: Sorted List
0 1 2 3 4
Ann
Dave
Recall: Sorted List
0 1 2 3 4
Ann Dave
Recall: Sorted List
0 1 2 3 4
Ann Dave
Humphry
Recall: Sorted List
0 1 2 3 4
Ann Dave Humphry
Recall: Sorted List
0 1 2 3 4
Ann Dave Humphry
Ben
Recall: Sorted List
0 1 2 3 4
Ann Dave Humphry
Ben
Recall: Sorted List
0 1 2 3 4
Ann Dave Humphry
Ben
Recall: Sorted List
0 1 2 3 4
Ann Dave HumphryBen
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
0 1 2 3 4
Ann Dave Humphry
Ben
First
0 1 2 3 4
Ann Dave Humphry
Ben
First
0 1 2 3 4
Ann Dave Humphry
Ben
First
0 1 2 3 4
Ann Dave Humphry
Ben
First
0 1 2 3 4
Ann Dave Humphry
First
Ben
0 1 2 3 4
Ann Dave Humphry Ben
First
0 1 2 3 4
Ann Dave Humphry Ben
First
0 1 2 3 4
Ann Dave Humphry Ben
First
Amy
0 1 2 3 4
Ann Dave Humphry Ben
First
Amy
0 1 2 3 4
Ann Dave Humphry Ben
First
Amy
0 1 2 3 4
Ann Dave Humphry Ben
First
Amy
0 1 2 3 4
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
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
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