Print Linked List elements
Problem​
Given a linked list. Print all the elements of the linked list.
Note: End of Line is handled by driver code itself. You just have to end with a single space.
Examples:​
Example 1:
Input:
LinkedList : 1 -> 2
Output:
1 2
Explanation:
The linked list contains two elements 1 and 2.The elements are printed in a single line.
Example 2:
Input:
Linked List : 49 -> 10 -> 30
Output:
49 10 30
Explanation:
The linked list contains 3 elements 49, 10 and 30. The elements are printed in a single line.
Your task:​
You don't need to read input or print anything. Your task is to complete the function display() which takes the head of the linked list as input and prints the linked list in a single line.
- Expected Time Complexity:
- Expected Auxiliary Space:
Constraints:​
- node values
Solution​
Python​
def display(self,head):
temp = head
while temp is not None:
print(temp.data, end = " ")
temp = temp.next
Java​
void display(Node head) {
Node temp = head;
while (temp != null) {
System.out.print(temp.data + " ");
temp = temp.next;
}
}
C++​
void display(Node *head) {
Node* temp = head;
while (temp != nullptr) {
cout << temp->data << " ";
temp = temp->next;
}
}
C​
void display(struct Node *head) {
struct Node* temp = head;
while (temp != NULL) {
printf("%d ", temp->data);
temp = temp->next;
}
}
- Time Complexity:
- Auxiliary Space: