User Tools

Site Tools


lists_ii

This is an old revision of the document!


Lists II

Although this is Lists II, you may wish to look at Basics III first to see how lists are used in a more complex program.

In this class we will examine exactly what a list is.

Class Node

class Node:
    def __init__(self, name):
        self.name = name
        self.next = 0

A node is a bit of data. A node contains a name, for exampe – the name of a fruit. It also contains special data which points to the next node. At the very least this is a bit of data called next, which shows the 'next node'.

A node is a node, which is a bit of information. This is the data structure. Next we need to define the algorithm(s) which operate on the data structure.

Class List

from Node import Node

class List:
    def __init__(self):
        self.root = 0
        self.last = 0

    def append(self, n):
        if isinstance(n, Node):
            if not isinstance(self.root, Node):
                self.root = n
                self.last = n
            else:
                self.last.next = n
                self.last = n

        else:
            print("Error: not a node")

    def print(self):
        n = self.root
        print(n.name)

        while isinstance(n.next, Node):
            n = n.next
            print(n.name)

    def printl(self):
        print("[", end = '')

        n = self.root
        while isinstance(n, Node):
            if n != self.root:
                print(' ', end = '')
            print("'", end = '')
            print(n.name, end = '')
            print("'", end = '')
            if isinstance(n.next, Node):
                print(',', end = '')
                n = n.next
            else:
                n = 0

        print("]")

under construction

FIXME

lists_ii.1698375287.txt.gz · Last modified: 2023/10/27 02:54 by appledog

Donate Powered by PHP Valid HTML5 Valid CSS Driven by DokuWiki