Quantcast
Channel: Active questions tagged python - Stack Overflow
Viewing all articles
Browse latest Browse all 23131

traversing Linked List python

$
0
0

take a look at this sample code:

class Dog:    def __init__(self,breed,name):        self.breed = breed        self.name = name    def bark(self):        print("my name is {}".format(self.name))class Cat:    def __init__(self,age):        self.age = age    def meow(self):        print("my name is {}".format(self.name))myDog = Dog("daschund","bingo")myCat = Cat(78)myCat.meow()

note: the class Cat does not inherit from the dog class. so when you try to run this code; it throws an attribute error since 'Cat' has no attribute called 'name'.

now take a look at this code for traversing a linked list

class Node():    def __init__(self,data=None,next=None):        self.data = data        self.next = next class LinkedList():    def __init__(self):        self.head = None    def print_linkedlist(self):        if self.head == None:            print("Linked list is empty!")        else:            n = self.head            while n != None:                print(n.data)                n = n.next

just like the initial example; here LinkedList has no attribute called data or next; because it doesn't inherit from the Node class. So how then does the print_linkedlist() method in the LinkedList class access the data and reference/pointer that the Node class contains?


Viewing all articles
Browse latest Browse all 23131

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>