Monday, December 9, 2013

A simple version of linked list in Python

It's quite simple to convert java code to Python code. Basically it's done by removing declaration of objects/variables/functions and keyword new
But there are two things you need to pay attention to when you do the conversion from java to Python.
1. null in java is replaced by None in Python.
2. Indentation in python. I debugged the python code for a while after converting it from a java code, which is posted in another post,  and found out it's due to a simple indentation issue.

Here goes the code:
#!/bin/python

class Node:
  pass

class LinkList:
  def __init__(self):
    self.head = None

  def isEmpty(self):
    return head == None

  def insert(self, a):
    node = Node()
    node.data = a
    node.next = None
    if self.head is None :
      self.head = node
    else:
      cursor = self.head
      last = self.head
      while (cursor is not None):
        if cursor.next is None:
          last = cursor
        cursor = cursor.next
      last.next = node

  def top(self):
    self.head = self.head.next

  def printList(self):
    cursor = self.head
    print  "List:  "
    while (cursor is not None):
      print cursor.data , " "
      cursor = cursor.next
    print

list = LinkList()
list.insert(1)
list.insert(2)
list.insert(3)
list.printList()
list.top()
list.printList()
list.top()
list.printList()

No comments:

Post a Comment