Given an array which is arranged in ascending order.. 3 Set the link field of a to point the node after CAT, which contains FAT.. Linked Ordered List Suppose elements are arranged in a
Trang 3 Insertion and deletion of arbitrary elements are
expensive.
Given an array which is arranged in ascending order.
delete the element ‘4’.
Storage allocation is not flexible.
Trang 4Possible Improvements
need to be stored in consecutive
Trang 64 5 6 7
8 9
8
first
Trang 74 5 6 7
8
8
first
1) Get a new node a 2) Set the data field of a to
EAT.
3) Set the link field of a to point
the node after CAT, which contains FAT.
Find the position where EAT is
3
4) Set the link field of the node
containing CAT to a.
Trang 84 5
6 7
8 9
8
first
1) Set the link of BAT to EAT 2) Deallocate CAT
Find the address of CAT
FAT 0
8 BAT 6
3
Trang 9Representation of a Linked List
Trang 11Linked Ordered List
Suppose elements are arranged in ascending
void Insert(DataField value);
bool Delete(DataField value); //return false if value is not found bool IsEmpty();
private:
ListNode *first;
Trang 12Initialization
Trang 15Boundary Condition: Case 1
There will be no previous node for AT.
The update of first is required.
first
AT
Trang 16Boundary Condition: Case 2
Trang 17 Always maintain two (dummy) nodes so that
insertion can always be performed between two nodes
Trang 18Improvement Using Two
first = new ListNode();
last = new ListNode();
Trang 19New Version of Insert()
01 void LinkedOrderList::Insert(DataField value)
Trang 23Performance Analysis
Suppose there are n nodes in a linked list.
store these n nodes.
O(1).
Time complexity to perform a insertion or deletion:
inserted and deleted at the end of the list Therefore,
the complexity is O(n).
memory space for a node increases loading for the OS
Trang 27Implementation of Linked Queue
LinkedQueue:: LinkedQueue() {
front = rear = NULL;
};
bool LinkedQueue::IsEmpty() {
if (front is NULL and rear is NULL) return true;
return false;
Trang 28rear = rear->link = new ListNode(value);
while (!IsEmpty()) Pop();
};
Trang 29using array and linked stack/queue
Memory space The length of an array is
fixed; Resize() is required
if the stack is full.
Memory space can be dynamically allocated The storage is more compact Execution time for
Push() and Pop() The time complexity is O(1) The time complexity is also O(1) But the memory
Trang 36}