Difference between revisions of "CSC212 Linked List in Python"
(Created page with "--~~~~ ---- <br /> =Source= <br /> <source lang="python"> # SLL in Python # D. Thiebaut # A simple program implementing a Singly-Linked List # in Python. # # The Node class: ...") |
(→Source) |
||
(One intermediate revision by the same user not shown) | |||
Line 21: | Line 21: | ||
class LList: | class LList: | ||
def __init__(self): | def __init__(self): | ||
− | self._head = _tail = None | + | self._head = self._tail = None |
def addFront( self, el ): | def addFront( self, el ): | ||
Line 60: | Line 60: | ||
</source> | </source> | ||
<br /> | <br /> | ||
+ | |||
=Output= | =Output= | ||
<br /> | <br /> | ||
Line 65: | Line 66: | ||
8 6 4 2 1 3 5 7 9 | 8 6 4 2 1 3 5 7 9 | ||
>>> | >>> | ||
+ | <br /> | ||
+ | ==Using Built-In Lists== | ||
+ | <br /> | ||
+ | <source lang="python"> | ||
+ | def main(): | ||
+ | L = [] | ||
+ | for i in range( 1, 10 ): | ||
+ | if i%2 == 0: | ||
+ | L.insert(0, i) | ||
+ | else: | ||
+ | L.append( i ) | ||
+ | |||
+ | print( L ) | ||
+ | |||
+ | main() | ||
+ | </source> | ||
+ | <br /> |
Latest revision as of 11:33, 7 October 2014
--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 = self._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()