Friday, March 21, 2014

Implement an algorithm to find the nth to last element of a singly linked list.

__author__ = 'nitin'

class Node:
    def __init__(self,initdata):
        self.data=initdata
        self.next=None
    def getData(self):
        return self.data
    def setData(self,item):
        self.data=item
    def getNext(self):
        return self.next
    def setNext(self,item):
        self.next=item

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

    def isEmpty(self):
        return self.head==None

    def add(self,item):
        temp=Node(item)
        temp.setNext(self.head)
        self.head=temp

    def find_nth_2_last(self,n):
        current=self.head
        sec_pointer=self.head
        count=1
        while current is not None and count            current=current.getNext()
            count +=1
        while current.getNext() is not None:
            current=current.getNext()
            sec_pointer=sec_pointer.getNext()
        return sec_pointer.getData()

mylist = UnorderedList()
mylist.add(7)
mylist.add(6)
mylist.add(5)
mylist.add(4)
mylist.add(3)
mylist.add(2)
mylist.add(1)

print mylist.find_nth_2_last(4)

No comments:

My Profile

My photo
can be reached at 09916017317