183 views
3 3 votes

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 = head
head = new_first

new_last = Node(30)
tail.next = new_last
tail = new_last

print(head.data, head.next.data, tail.data, head.next.next.data)

What is the output of the code above?

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

1 Answer

1 1 vote

Initially:

head -> 20
tail -> 20

Now a new node is inserted at the beginning:

new_first = Node(10)
new_first.next = head
head = new_first

So the list becomes:

10 -> 20

The tail is still pointing to node $20$.

Now a new node is inserted at the end:

new_last = Node(30)
tail.next = new_last
tail = new_last

So the list becomes:

10 -> 20 -> 30

Therefore:

head.data = 10
head.next.data = 20
tail.data = 30
head.next.next.data = 30

The output is:

10 20 30 30

Correct Option: A

Answer:
Position:
Show:

Related questions

3 3 votes
1 1 answer
203
203 views
GO Classes asked Jun 29
203 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 ...
3 3 votes
1 1 answer
170
170 views
GO Classes asked Jun 29
170 views
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 ...
3 3 votes
2 2 answers
227
227 views
GO Classes asked Jun 29
227 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...
4 4 votes
2 2 answers
210
210 views
GO Classes asked Jun 29
210 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...