115 views
2 2 votes

Consider the following Python code:

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

n1 = Node(5)
n2 = Node(10)
n3 = Node(15)
n4 = Node(20)

n1.next = n2
n2.next = n3
n3.next = n4

t = n1
count = 0
total = 0

while t is not None:
    count = count + 1
    total = total + t.data
    t = t.next

print(count, total)

What is the output of the code above?

  1. 3 30
  2. 4 50
  3. 4 45
  4. 5 50

1 Answer

0 0 votes

The linked list is:

5 -> 10 -> 15 -> 20 -> None

The variable $\texttt{t}$ starts from $\texttt{n1}$.

The loop runs while $\texttt{t is not None}$. In each iteration:

count = count + 1
total = total + t.data
t = t.next

Step-by-step traversal:

Node 1: data = 5,  count = 1, total = 5
Node 2: data = 10, count = 2, total = 15
Node 3: data = 15, count = 3, total = 30
Node 4: data = 20, count = 4, total = 50

After node $4$, $\texttt{t}$ becomes $\texttt{None}$, so the loop stops.

Therefore, the output is:

4 50

Correct Option: B

Answer:
Position:
Show:

Related questions

2 2 votes
1 1 answer
148
148 views
GO Classes asked Jun 29
148 views
Consider the following Python code:class Node: def __init__(self, data): self.data = data self.next = None a = Node("A") b = Node("B") c = Node("C") d = Node("D") a.next ...
2 2 votes
1 1 answer
123
123 views
GO Classes asked Jun 29
123 views
Consider the following Python code:class Node: def __init__(self, data): self.data = data self.next = None head = Node(20) tail = head new_first = Node(10) new_first.next...
2 2 votes
2 2 answers
175
175 views
GO Classes asked Jun 29
175 views
Consider the following Python code:class Node: def __init__(self, data): self.data = data self.next = None a = Node("A") b = Node("B") c = Node("C") a.next = b b.next = c...
3 3 votes
2 2 answers
156
156 views
GO Classes asked Jun 29
156 views
Consider the following Python code:class Node: def __init__(self, value): self.value = value self.next = None n1 = Node(10) n2 = Node(20) print(n1.value, n1.next, n2.valu...