edited by
357 views
3 3 votes
class Node:
    def __init__(self, data, next=None):
        self.data = data
        self.next = next

def print_nodes(ptr):
    if ptr:
        print(ptr.data, end=' ')
        while ptr.next:
            ptr = ptr.next
            print(ptr.data, end=' ')

What is the output, if the address of the first node of singly linked list $1 \rightarrow 2 \rightarrow 3\rightarrow 4 \rightarrow 5$ is passed in the above python code?

  1. $1\; 2 \;3\; 4\; 5$
  2. $1\; 1\; 2\; 3\; 4\; 5$
  3. $1\; 1\; 2\; 3\; 4\; 5\; 5$
  4. None of these

1 Answer

3 3 votes

The given code defines a class Node and a function print_nodes that prints the elements of a singly linked list.
Let's analyze the print_nodes function:

  1. If the input pointer ptr is not None, it prints the data of the first node.
  2. It then enters a while loop that continues as long as ptr.next is not None. Inside the loop, ptr is moved to the next node, and the data of each node is printed.

Given Linked List:

1 → 2 → 3 → 4 → 5

The first print statement prints the data of the first node: 1.

The while loop then iterates over the remaining nodes, printing their data: 2, 3, 4, and 5.

Output:

The output will be: 1 2 3 4 5, which matches the format 12345.

Correct Answer: A. 12345.

edited by
Answer:
Position:
Show:

Related questions

1 1 vote
1 1 answer
435
435 views
GO Classes asked Sep 15, 2024
435 views
Consider the following code fragment.class Node: def __init__(self, data, next=None): self.data = data self.next = next def invert_list(front): curr = front prev = None n...
3 3 votes
1 1 answer
591
591 views
GO Classes asked Sep 15, 2024
591 views
The following code is intended to remove a node p from a doubly linked list. Assume that we know that p is in the list, so the list is not empty.class Node: def __init__(...
4 4 votes
2 2 answers
432
432 views
GO Classes asked Sep 15, 2024
432 views
Consider a mutual pair of recursive functions g() and h().class Node: def __init__(self, value, next=None): self.value = value self.next = next def g(l): if l is None or ...
0 0 votes
2 2 answers
367
367 views
GO Classes asked Sep 15, 2024
367 views
Consider the following function that takes reference to head of a Doubly Linked List as parameter. Assume that a node of doubly linked list has previous pointer as $\text...