CSC212 Linked List in Python

From dftwiki3
Revision as of 10:34, 3 October 2014 by Thiebaut (talk | contribs) (Output)
Jump to: navigation, search

--D. Thiebaut (talk) 19:53, 2 October 2014 (EDT)



Source


# SLL in Python
# D. Thiebaut
# A simple program implementing a Singly-Linked List
# in Python.
#

# The Node class: this is the basic element of the linked list.
class Node:    
    def __init__( self, el, link ):
        self.info = el
        self.next = link

# The linked list class.  Contains only a head and tail pointer.
# AddFront(), addTail, and printAll are supported.
class LList:
    def __init__(self):
        self._head = _tail = None

    def addFront( self, el ):
        if self._head == None:
            self._tail = self._head = Node( el, None )
        else:
            self._head = Node( el, self._head )

    def addTail( self, el ):
        if self._head==None:
            self.addFront( el )
        else:
            self._tail.next = Node( el, None )
            self._tail = self._tail.next

    def printAll( self ):
        it = self._head
        while it != None:
            print( it.info, " ",sep='', end='' )
            it = it.next
        print()

# test the LinkedList by adding a few in the front and at
# the tail end.
def main():
    linkedList = LList()
    for i in range( 1, 10 ):
        if i%2 == 0:
            linkedList.addFront( i )
        else:
            linkedList.addTail( i )

    linkedList.printAll()

main()


Output


>>> 
8 6 4 2 1 3 5 7 9 
>>>


Using Built-In Lists


def main():
    L = []
    for i in range( 1, 10 ):
            if i%2 == 0:
                L.insert(0, i)
            else:
                L.append( i )

    print( L )

main()