Linked List PPT Cs A Level
Linked List PPT Cs A Level
Learning Objectives
In this session, you will be able to:
The algorithm must check for an empty free list as there is then
no way of adding new data. It must also check to see if the
new data is to be inserted at the front of the list. If neither of
these is needed, the algorithm must search the list to find the
position for the new data.
Deletion
Suppose we wish to delete the third cell in the
linked list.
Linear List Vs Linked List
In real applications, the data would consist of much
more than a keyfield and one data item. When list
elements need reordering, only pointers need
changing in a linked list.
Unlike in a linear list, all data items would need to
be moved.
Using linked list saves time, however, we need more
storage space for the pointer fields.
Linked List Implementation Using Array
An integer array storing the indexes that create the links, e.g.
link[20]
The head pointer stores the index position of the first item in the list.
Create a new Linked List
CONSTANT NullPointer = -1
TYPE ListNode
DECLARE Data: STRING
DECLARE Pointer: INTEGER
ENDTYPE PROCEDURE InitialiseList
DECLARE StartPointer: INTEGER StartPointer = NullPointer
FreeListPtr = 0
DECLARE FreeListPtr: INTEGER FOR Index = 0 TO N-1
DECLARE List[1:N] OF ListNode List[Index].Pointer = Index + 1
ENDFOR
List[N].Pointer = NullPointer
ENDPROCEDURE
Insert a new node
PROCEDURE InsertNode(NewItem)
IF FreeListPtr <> NullPointer
THEN //There is space in the array
//Take node from free list and store data item
NewNodePtr = FreeListPtr
List[NewNodePtr].Data = NewItem
FreeListPtr = List[FreeListPtr].Pointer
//find insertion point
PreviousNodePtr = NullPointer
ThisNodePtr = StartPointer //start at beginning of list
WHILE ThisNodePtr <> NullPointer //while not end of list
AND List[ThisNodePtr].Data < NewItem
PreviousNodePtr = ThisNodePtr
ThisNodePtr = List[ThisNodePtr].Pointer
ENDWHILE
Insert a new node (cont’d)
IF PreviousNodePtr = NullPointer
THEN //insert new node at start of list
List[NewNodePtr].Pointer = StartPointer
StartPointer = NewNodePtr
ELSE //insert new node after first node
List[NewNodePtr].Pointer = List[PreviousNodePtr].Pointer
List[PreviousNodePtr].Pointer = NewNodePtr
ENDIF
ELSE
PRINT “No more space”
ENDIF
ENDPROCEDURE
Find an element
FUNCTION FindNode(DataItem) RETURNS INTEGER
CurrentNodePtr = StartPointer