Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # NullPointer should be set to -1 if using array element with index 0
- NULLPOINTER = -1
- # Declare record type to store data and pointer
- class ListNode:
- def __init__(self):
- self.Data = ""
- self.Pointer = NULLPOINTER
- def InitialiseList():
- List = [ListNode() for i in range(8)]
- StartPointer = NULLPOINTER # set start pointer
- FreeListPtr = 0 # set starting position of free list
- for Index in range(7): # link all nodes to make free list
- List[Index].Pointer = Index + 1
- List[7].Pointer = NULLPOINTER # last node of free list
- return (List, StartPointer, FreeListPtr)
- def InsertNode(List, StartPointer, FreeListPtr, NewItem):
- if FreeListPtr != NULLPOINTER:
- # 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 and List[ThisNodePtr].Data < NewItem:
- # while not end of list
- PreviousNodePtr = ThisNodePtr # remember this node
- # follow the pointer to the next node
- ThisNodePtr = List[ThisNodePtr].Pointer
- if PreviousNodePtr == NULLPOINTER:
- # insert new node at start of list
- List[NewNodePtr].Pointer = StartPointer
- StartPointer = NewNodePtr
- else: # insert new node between previous node and this node
- List[NewNodePtr].Pointer = List[PreviousNodePtr].Pointer
- List[PreviousNodePtr].Pointer = NewNodePtr
- else:
- print("no space for more data")
- return (List, StartPointer, FreeListPtr)
- List, StartPointer, FreeListPtr = InitialiseList()
- List, StartPointer, FreeListPtr = InsertNode(List, StartPointer,FreeListPtr, "A")
- List, StartPointer, FreeListPtr = InsertNode(List, StartPointer,FreeListPtr, "B")
- OutputAllNodes(List, StartPointer)
- ```
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement