Chapter 2 Arrays Iteration Invariants
Chapter 2 Arrays Iteration Invariants
• also Add(value)
• Pre: value is the value to be added to the list
• Post: value has been placed at the tail of the list
• n <- node(value)
• if head = fi
• head <- n
• tail<- n
• else
• Next <- n
• tail <- n
• end if
• end Add
Searching in Linked Lists
Searching a linked list is straightforward: we
simply traverse the list checking the value we
are looking for with the value of each node in
the linked list.
• also Contains(head, value)
• Pre: the head is the head node in the list
• value is the value to search for
• Post: the item is either in the linked list, true; otherwise false
• n <- head
• While n 6= fi and n.Value 6= value
• n <- n.Next
• end while
• if n = fi
• return false
• end if
• return true
• end Contains
Deletion in Linked Lists
Deleting a node from a linked list is straight-forward,
but there are some cases that you need to account for:
• the list is empty; or
• the node to remove is the only node in the linked
list; or
• we are removing the head node; or
• we are removing the tail node; or
• the node to remove is somewhere in between the
head and tail; or
• the item to remove doesn't exist in the linked list
Algorithm for Deletion
• algorithm Remove(head, value)
• Pre: the head is the head node in the list
• value is the value to remove from the list
• Post: value is removed from the list, true; otherwise false
• if head = fi
• return false
• end if
• n <- head
• If n.Value = value
• if the head = tail
• head <- fi
• tail <- fi
• else
• HHead <- head.Next
• end if
• return true
• end if
• while n.Next 6= fi and n.Next.Value 6= value
• n <- n.Next
• end while
• if n.Next 6= fi
• if n.Next = tail
• tail <- n
• end if
• // this is only case 5 if the conditional on line 25 was false
• Next <- n.Next.Next
• return true
• end if
• return false
• end Remove