Linked Lists
Linked Lists
a b c d
head = NULL;
head
current
x
tmp
tmp = new Node;
tmp->element = x;
tmp->next = current->next;
current->next = tmp;
a x b
… …
current
a b c d
Empty List
header
a b c
Advantages:
• Convenient to traverse the list backwards.
• Simplifies insertion and deletion because you no longer
have to refer to the previous node.
Disadvantage:
• Increase in space requirements.
oldNode = current;
oldNode->prev->next = oldNode->next;
oldNode->next->prev = oldNode->prev;
delete oldNode;
current = head;
private:
ListNode<Object> *current; // Current position
private:
ListNode<Object> *header;
};
CENG 213 Data Structures 23
Some List one-liners
/* Construct the list */
template <class Object>
List<Object>::List( )
{
header = new ListNode<Object>;
}
/* Test if the list is logically empty.
* return true if empty, false otherwise.*/
template <class Object>
bool List<Object>::isEmpty( ) const
{
return header->next == NULL;
}
printList( theList );
for( i = 0; i < 10; i++ )
{ theList.insert( i, theItr );
printList( theList );
theItr.advance( );
}
for( i = 0; i < 10; i += 2 )
theList.remove( i );
List<int> list2;
list2 = theList;
printList( list2 );
return 0;
} CENG 213 Data Structures 34
Comparing Array-Based and Pointer-
Based Implementations
• Size
– Increasing the size of a resizable array can waste
storage and time
• Storage requirements
– Array-based implementations require less memory than
a pointer-based ones
– writeListBackward2 strategy
• Write the list minus its first node backward
• Write the first node of the list
• Recursive view of a sorted linked list
– The linked list to which head points is a sorted list if
• head is NULL or
• head->next is NULL or
• head->item < head->next->item, and
head->next points to a sorted linked list