css342: linked lists1 professor: munehiro fukuda
TRANSCRIPT
CSS342: Linked Lists 1
CSS342: Linked Lists
Professor: Munehiro Fukuda
CSS342: Linked Lists 2
Topics
• Basic concepts of linked lists
• Implementations
• Special implementations
• Applications
CSS342: Linked Lists 3
Linked List
template<class Object>struct LListNode { Object item; LListNode *next;};
template<class Object>class LList { public: LList( ); LList( const LList &rhs ); ~LList( );
bool isEmpty( ) const; void clear( ); void insert( const Object &x, int index ); // insert a new item right after the index int find( const Object &x ) const; void remove( const Object &x ); const LList &operator=( const LList &rhs ); private: LListNode<Object> *header;
LListNode<Object> *findByIndex( int index ) const; LListNode<Object> *findPrevious( const Object &x ) const;};
20 45 51 76 84
60Removed item
Inserted item
NULLX
X == 45
header
Basic Concepts
CSS342: Linked Lists 4
STL Class list#include <list>list( ); list(size_type num, const T& value); list( const list<T>& anotherList);Constructors. See the text page 221 for more details.Example: list<int> list1; list<string> list2(10, “straightB”);bool empty( ) const;Returns true if the list has no elements.Example: while (list1.empty( ) == false) { …} iterator begin( );Returns an iterator that references the first element.If there is nothing, it is the same as the value returned by end( ) Example: list<string>::iterator i = list2.begin( ); if ( i != list2.end( ) ) cout << *I << endl; iterator end( );Return the end marker.Example: see begin( ).size_type size() const;Returns the number of elements. Size_type is an integral type. You can compare it with an integer.Example: while (list1.size( ) > 0) { … }iterator insert(iterator position, const T& value); Inserts an item value immediately before the element specified by the iterator position.Example: list<string>::iterator i = list2.insert (10, “abc”); void remove (const T& value);Removes all items with value from the list.Example: list2.remove(“straightB”);iterator erase( iterator position );Removes the item pointed to by iterator position.Example: list1.erase( 2 );void push_back(const T& x); void push_front(const T& x); T& front(); void clear(); void pop_front();void pop_back(); void reverse(); See your own C++ textbook or http://www.cppreference.com/
Basic Concepts
CSS342: Linked Lists 5
STL Class listExample
#include <list>#include <iostream>#include <string>using namespace std;
int main( ) { list<string> facultyList; list<string>::iterator i = facultyList.begin( );
i = facultyList.insert( i, “berger” ); i = facultyList.insert( i, “cioch” ); i = facultyList.insert( i, “fukuda” );
cout << “#faculty members: “ << facultyList.size( ) << endl;
for (i = facultyList.begin( ); i != facultyList.end( ); i++ ) cout <<*i << endl;}
Results (= inputs are reversed):#faculty members: 3fukudaciochberger
Basic Concepts
CSS342: Linked Lists 6
Array-Based List Implementation
• Easy implementation
• Fixed list size
• Necessity to shift data down to an extended space upon an insertion and to shift data up upon a deletion– What is big-O for those operations?
• Find
• Insert
• Delete
list[0]list[1]
list[3]list[2]
list[4]
list[n]list[n-1]
Implementation
CSS342: Linked Lists 7
Merits of Linked List• Each item points to its successor
• Arbitrary list size
• No shift operations
• Pointer operations required
20 45 51 76 84
20 45 51 76 84
60Deleted item
Inserted item
NULL
NULL
Implementation
CSS342: Linked Lists 8
Pointer-Based Linked Listprivate data items
• List elementstruct LListNode{ Object item;
Node *next;}
• Header pointerLListNode *header;If header == NULL, list is empty.
item nextitem next
item
Object LListNode*
Object* Object
LListNode
header
head
item next item next NULL
NULL
Implementation
CSS342: Linked Lists 9
insert( &Object newValue, int index) Inserting a New Node (after an Index)
• Creating a new node– LListNode *newptr = new Node;– newPtr->item = newValue;
• Inserting a node between nodes– newPtr->next = current->next;– current->next = newPtr;
• Inserting a node at the top– newPtr->next = head;– header = newptr;
• Should we really distinguish these two cases?
51 76
60
NULLheader
curcurrent
51 76
60
NULLheader
current
NULL
Current actually cannot point to header!
Implementation
index newValue
CSS342: Linked Lists 10
insert( )Node Definition Revisited
• List elementstruct LListNode{ Object item;
Node *next;}
• Header pointer and node// adding a dummy header nodeLListNode *header = new Node;header->next = null;
If head->next == NULL, list is empty.
• Node Insertion– LListNode *newptr = new Node;– newPtr->item = newValue;– newPtr->next = current->next;– current->next = newPtr;
header
header
item next item next NULL
NULLitem next
dummy header0th element 1st node
current
dummy header0th element
newValue
next
newptr
X
Implementation
CSS342: Linked Lists 11
remove( const Object &x )Removing a Given Node
• Stop the current pointer at the node previous to a deleted node (with findPrevious( ))
• Memorize the node to remove LListNode *deletedNode = current->next;
• Remove this nodecurrent->next = current->next->next;
• Deallocating the nodedelete deletedNode;
20 45 NULL76header
current
NULL
dummy
Implementation
x
Node to be deleted
CSS342: Linked Lists 12
int find( const Object &x )Finding a Position That Includes X
for (LListNode *p = header->next; p != NULL && p->element != x; p = p->next );
header NULL6051
p
pIteration 1:Iteration 2:
Iteration 3:
dummy
p
X
Exited from here
Implementation
CSS342: Linked Lists 13
LListNode<Object> *findByIndex( int index ) Finding a Position by an Index
header NULL6051
p
pindex 0:index 1:
index 2:
dummy
p
index = 2
Exited from here
template<class Object>LListNode<Object> *LList<Object>::findByIndex( int index ) const { if ( index < 0 ) return NULL;
LListNode<Object> *p = header; for ( int i = 0; p != NULL; p = p->next, i++ ) if ( i == index ) break; return p;}
Implementation
Note: index 0 is a dummy
CSS342: Linked Lists 14
LListNode<Object> *findPrevious( Object &x )Finding the Node Previous to the One to Be Deleted
for (LListNode *p = header; p->next != NULL && p->next->item != x; p = p->next);
header 5551
p
pIteration 1:Iteration 2:
Iteration 3:
dummy
p Exitted from here
NULL60X
Iteration 4: p
Implementation
CSS342: Linked Lists 15
~LList( ) Destructor
• Deallocate all pointer variables
20 45 51 NULLhead
45 51 NULLhead
51 NULLhead
findByIndex(1)
findByIndex(1)
findByIndex(1)
template<class Object>LList<Object>::~LList( ) { clear( ); delete header;}
template<class Object>void LList<Object>::clear( ) { while ( !isEmpty( ) ) { LListNode<Object> *node = findByIndex( 1 ); remove( node->item ); }}
Implementation
CSS342: Linked Lists 16
LList( const LList &rhs ) Copy Constructor
• Implicit called upon passing, returning, and assigning an object.
• Shallow copy: C++ and Java’s operator= copies an object’s data members.
• Deep copy: Java’s clone( ) copies all traversable pointer variables.
20 45 51 76 NULLheader
copy of header
20 45 51 76 NULLheader
copy of header 20 45 51 76 NULL
Implementation
CSS342: Linked Lists 17
template<class Object>const LList<Object> &LList<Object>::operator=( const LList &rhs ) { if ( this != &rhs ) { // why do we have to check ? clear( ); // why do we have to call clear( )?
int index; LListNode<Object> *rnode; for ( index = 0, rnode = rhs.header->next; rnode != NULL;
rnode = rnode->next, ++index ) insert( rnode->item, index ); // insert rnode’s item after index } return *this;}template<class Object>LList<Object>::LList( const LList &rhs ) { header = new LListNode<Object>; header->next = NULL; *this = rhs;}
45 51 76 NULLheader
copy of header 45 51 76 NULL
rhs
this
dummy
dummy
index 0
copy copy copy
Implementation
LList( const LList &rhs ) Copy Constructor
CSS342: Linked Lists 18
Entire Implementation#ifndef _LLIST_CPP_#define _LLIST_CPP_
#include <iostream>using namespace std;
template<class Object>LList<Object>::LList( ) { header = new LListNode<Object>; header->next = NULL;}
template<class Object>LList<Object>::LList( const LList &rhs ) { header = new LListNode<Object>; header->next = NULL; *this = rhs;}
template<class Object>LList<Object>::~LList( ) { clear( ); delete header;}
template<class Object>bool LList<Object>::isEmpty( ) const { return header->next == NULL;}
template<class Object>void LList<Object>::clear( ) { while ( !isEmpty( ) ) { LListNode<Object> *node = findByIndex( 1 ); remove( node->item ); }}
template<class Object>void LList<Object>::insert( const Object &x, int index ){ LListNode<Object> *current = findByIndex( index );
LListNode<Object> *newPtr = new LListNode<Object>; newPtr->item = x; newPtr->next = current->next; current->next = newPtr;}
template<class Object>int LList<Object>::find( const Object &x ) const { LListNode<Object> *p = header->header; int i = 0; for ( ; p != NULL && p->item != x; p = p->next, ++i ); return ( p == NULL ) ? -1 : i;}
1/4 2/4
Implementation
CSS342: Linked Lists 19
Entire Implementation (Cont’d)
template<class Object>void LList<Object>::remove( const Object &x ) { LListNode<Object> *current = findPrevious( x ); if ( current == NULL ) return;
LListNode<Object> *deletedNode = current->next; current->next = current->next->next; delete deletedNode;}
template<class Object>const LList<Object> &LList<Object>::operator=( const LList &rhs ) { if ( this != &rhs ) { clear( );
int index; LListNode<Object> *rnode; for ( index = 0, rnode = rhs.header->next; rnode != NULL;
rnode = rnode->next, ++index ) insert( rnode->item, index ); } return *this;}
3/4
Implementation
CSS342: Linked Lists 20
Entire Implementation (Cont’d)
template<class Object>
template<class Object>LListNode<Object> *LList<Object>::findByIndex( int index ) const { if ( index < 0 ) return NULL;
LListNode<Object> *p = header; for ( int i = 0; p != NULL; p = p->next, i++ ) if ( i == index ) break; return p;}
template<class Object>LListNode<Object> *LList<Object>::findPrevious( const Object &x ) const{ LListNode<Object> *p;
for ( p = header; p->next != NULL && p->next->item != x; p = p->next );
return p;}
#endif
4/4
Implementation
CSS342: Linked Lists 21
ofstream outFile(filename);for (LListNode *cur = head->next; cur != NULL; cur = cur->
next ) {outFile << cur->item << endl;outFile << cur->next << endl; // Must it be saved?
}outFile.close( );
Saving a Linked List in a File
45 51 NULLhead 45 51 EOF
SaveFileLinked list
Cur->next, memory address has no meaning when reloaded
dummy
Implementation
CSS342: Linked Lists 22
Restoring a Linked List from a FileLListNode *tail = header;while ( inFile >> nextItem ){ tail->next = new Node; // 1. Allocate a new node next to the tail
tail = tail->next; // 2. Have the tail point to the new nodetail->item = nextItem; // 3. Put the new item in the nodetail->next = NULL; // 4. Set the pointer in the new node to NULL
}
20 45 NULLheader20 45 51 EOF
tail
12
NULL4RestoreFile Linked list
How about the first node?
3
51
dummy
Implementation
CSS342: Linked Lists 23
Array-based:• Advantages:
– Easy to use
– A good choice for a small list
– O(1) access time
• Disadvantages:– space and time wasting in
dynamic array
Pointer-Based:• Advantages:
– Arbitrary size
– No shift required
• Disadvantages:– Necessity to allocate next
– O(N) access time
Array-Based v.s. Pointer-Based Implementation
Implementation
We would like to mitigate this O(N) access time
CSS342: Linked Lists 24
Circular Linked Lists• Linear linked lists: grocery, inventory, and customer lists
• Circular linked lists: login users list
• Traverse in circular linked lists:LListNode *first = list; // list points the 1st dummy node LListNode *cur = first->next;while ( cur != first ) { display(cur->item);
cur = cur->next;};
45 51 NULLhead
45 51list
Special Implementation
dummy
dummy
CSS342: Linked Lists 25
Doubly Linked Lists
NULL45 73 51NULL
head
45 73 51 NULLhead
Single Linked Lists
To be deleted
Precedent must be kept track of.
Doubly Linked Lists
cur->prev->next = cur->nextBut pointer operations become more complicated.
dummy
dummy
Special Implementation
CSS342: Linked Lists 26
Circular doubly linked list with a dummy head node
45 73 5120
head
Traversing a node:cur = head->next;while (cur != head && newItem != cur->item)
cur = cur->next;Deleting a node:
cur->prev->next = cur->next;cur->next->prev = cur->prev
dummy
Special Implementation
CSS342: Linked Lists 27
Inserting a Nodebefore the current pointer
45
7320
newPtr->next = cur; // (a)newPrt->prev = cur->prev; // (b)cur->prev = newPtr; // (c)newPtr->prev->next = newPtr; // (d)
cur
(a)
(b) (c)
(d)
Special Implementation
CSS342: Linked Lists 28
Move-To-Front List• int find( const Object &x ) {
– Move the item found to the top.
}
Special Implementation
NULL45 7351NULL
head
dummy
51
To the front
CSS342: Linked Lists 29
Transpose List
• int find( const Object &x ) {– Swap the item with its previous item.
}
Special Implementation
NULL45 7351NULL
head
dummy
51
swap
CSS342: Linked Lists 30
Skip Listhttp://en.wikipedia.org/wiki/Skip_list (designed in 1990)
Special Implementation
– ∞
– ∞
– ∞
– ∞
– ∞
– ∞
12
12
17
17
17
17
17
20
25
25
25
25
31
31
31
39 50
55
55
55
55
+ ∞
+ ∞
+ ∞
+ ∞
+ ∞
+ ∞
S5
S4
S3
S2
S1
S0
Search for 39
Insert 31
rand( ) % 2 = 1
rand( ) % 2 = 1
Delete 31
CSS342: Linked Lists 31
Single Linked List Application
• FAT has an entry for each disk block.
• FAT entries rather than blocks themselves are linked.
• Example:– MS-DOS and OS/2
• Merit: – Save disk block space– Faster random accesses
• Demerit: – A significant number of
disk head seeks
test 217name start block
directory entry
339
618
EOF
0
217
339
618
#blocks -1FAT
217
339
618
Applications
• File Allocation Table (FAT)
CSS342: Linked Lists 32
Circular List Application
• Round-Robin Based Job Scheduling
Applications
CPURegisters
PageTable
FileDescriptors
Prog name“emacs”
Process ID100
CPURegisters
PageTable
FileDescriptors
Prog name“g++”
Process ID105
CPURegisters
PageTable
FileDescriptors
Prog name“a.out”
Process ID99
CPURegisters
PageTable
FileDescriptors
Prog name“ps2pdf”
Process ID217
head
CSS342: Linked Lists 33
Doubly Linked List Application
• Line-based text editors like Unix ed
Applications
int main( ) {
int a = 3, b = 5;
cout << a + b << endl;
}
NULL
string
NULLHEADER
CSS342: Linked Lists 34
MTF List Application
• No more free frame
• Find a victim page
– Paging out M cause another page fault
– Paging out H may be okay.
– Algorithm to minimize page faultsH
Load M
J
M
A
B
D
E
OS
OS
D
H
J
A
E
3 vi
5 vi
6 vi
2 v7 v
Process 1’s logical memory
Process 2’s logical memory
Proc1’s page table
Proc2’s page table
0
1
2
1
0
1
2
3
0
1
2
3
4
5
6
7
Physical memory
PC
PC
Load M
M
4 v
B?
Applications
• Page Replacement
CSS342: Linked Lists 35
LRU Implementation with MTF List
• Replace a least recently used page with a new page.
Applications
pageD
pageH
pageJ
pageE
pageB
pageM
pageA
Swap out
pageD
pageH
pageJ
pageE
pageM
pageA
pageB
2. Access page H
1. Swap in page B
pageH
pageJ
pageE
pageM
pageA
pageB
3. Swap in D againSwap out
Move to Front
LRU page