Title: INFSCI 0015 Data Structures Lecture 20: Linear Lists
1INFSCI 0015 - Data StructuresLecture 20 Linear
Lists
- Peter Brusilovsky
- http//www2.sis.pitt.edu/peterb/0015-011/
2From Data to Data Structures
machine level data storage
0100110001101001010001
primitive data types
28
3.1415
'A'
array
structure
basic data structures
high-level data structures
stack
queue
list
3Some Data Structures
4Linear list
- A sequence of elements
- There is first and last element
- Each element has previous and next
- Nothing before first
- Nothing after last
5What makes a special kind of list
- What we can do with a linear list?
- Delete element
- Insert element
- Find element
- Traverse list
- Is the list sorted or not?
- Numerically
- Alphabetically
- Any other way
6Some classification of lists
7Insert list, data ? new list
8Retrieve list, criteria ? element
9Delete list, criteria ? new list
10Traverse list ? elements in order
- get_first(list) -
- returns first element if it exists
- get_next(list) -
- returns next element if it exists
- Both functions return NULL otherwise
- Calling get_next in a loop we will get one by one
all elements of the list
11How we can implement a list?
- Array?
- Search is easy (sequential or binary)
- Traversal is easy
- for(i first i lt last i)
- process(ai)
- Insert and delete is not easy
- a good part of the array has to be moved!
- Hard to guess the size of an array
12A linked list implementation
- Linked list is a chain of elements
- Each element has data part and link part pointing
to the next element
13A Node - an element of the LL
14Head and Node are Structures
- We need to define two structures one for a list
head, one for a list node
15Head and Node simple int list
head
count
- struct intlist
- struct node head
- int count
-
- struct node
- int data
- struct node link
2
15
data
link
99
data
link
16Head and Node name list
- struct intlist
- struct node head
- int count
-
- struct node
- char name
- struct node link
17Head and Node structure as data
- struct intlist
- struct node head
- int count
-
- struct node
- struct person data
- struct node link
-
- struct person
- char name
- int age
18Main operations
- Create list
- Add node
- beginning,middle or end
- Delete node
- beginning,middle or end
- Find node
- Traverse list
19Create list
20Add Empty list
21Add At the beginning of the list
22Add In the middle of the list
23Add At the end of the list
24Delete first
25Delete General case
26(No Transcript)
27Traversing the list
- struct intlist mylist
- for(pWalker mylist.head
- pWalker ! NULL
- pWalker pWalker-gtlink)
- process(pWalker-gtdata)
-
28Traversing list as ADT
- We need an extra pointer to store current
position - get_first will set pos head
- get_next will set pos pos-gtlink