Question 2:
The insert function has parameters: a pointer to a Node named , and an integer value, .
The constructor for Node has parameter: an integer value for the field.
The constructor for Node has parameter: an integer value for the field.
Output Format
Your insert function should return a reference to the node of the linked list.
Sample Input
The following input is handled for you by the locked code in the editor:
The first line contains T, the number of test cases.
The subsequent lines of test cases each contain an integer to be inserted at the list's tail.
The first line contains T, the number of test cases.
The subsequent lines of test cases each contain an integer to be inserted at the list's tail.
4
2
3
4
1
The locked code in your editor prints the ordered data values for each element in your list as a single line of space-separated integers:
2 3 4 1
Solution:
class Node:
def __init__(self,data):
self.data = data
self.next = None
class Solution:
def display(self,head):
current = head
while current:
print(current.data,end=' ')
current = current.next
def insert(self,head,data):
#Complete this method
if (head==None):
newnode=Node(data)
head=newnode
elif(head.next==Node):
newnode=Node(data)
head.next=newnode
else:
head.next=mylist.insert(head.next,data)
return head
mylist= Solution()
T=int(input())
head=None
for i in range(T):
data=int(input())
head=mylist.insert(head,data)
mylist.display(head);
0 Comments