165 views
3 3 votes

Consider the following Python code:

class Node:
    def __init__(self, data):
        self.data = data
        self.next = None

n1 = Node(10)
n2 = Node(20)
n3 = Node(30)

n1.next = n2
n2.next = n3

n2.data = n1.data + n3.data

print(n1.data, n1.next.data, n1.next.next.data)

What is the output of the code above?

  1. 10 20 30
  2. 10 40 30
  3. 40 40 30
  4. 10 30 40

1 Answer

1 1 vote

A linked list is made using nodes. Each node can store data and a reference to the next node.

Initially:

n1.data = 10
n2.data = 20
n3.data = 30

These statements create links between the nodes:

n1.next = n2
n2.next = n3

So:

n1.next.data = n2.data
n1.next.next.data = n3.data

Now:

n2.data = n1.data + n3.data
n2.data = 10 + 30 = 40

Therefore:

n1.data = 10
n1.next.data = n2.data = 40
n1.next.next.data = n3.data = 30

The output is:

10 40 30

Correct Option: B

Answer:
Position:
Show:

Related questions

2 2 votes
1 1 answer
146
146 views
GO Classes asked Jun 27
146 views
Consider the following Python code:class Batch: def __init__(self, name, count): self.name = name self.count = count def shift(self, other, n): self.count = self.count - ...
2 2 votes
1 1 answer
144
144 views
GO Classes asked Jun 27
144 views
Consider the following Python code:class Box: def __init__(self, value): self.value = value def add(self, value): self.value = self.value + value value = value + 100 retu...
2 2 votes
1 1 answer
146
146 views
GO Classes asked Jun 27
146 views
Consider the following Python code:class Account: def __init__(self, balance): self.balance = balance def deposit(self, amount): self.balance = self.balance + amount retu...
1 1 vote
1 1 answer
157
157 views
GO Classes asked Jun 27
157 views
Consider the following Python code:class Faculty: def __init__(self, name, subject): self.name = name self.subject = subject f1 = Faculty("Sachin", "Python") f2 = Faculty...