Practice Problem Link: Print Linked List
Please make sure to try solving the problem yourself before looking at the editorial.
Problem Statement
Given a linked list, print all its nodes.
Approach
The idea is simply to traverse the given linked list and print the value of every node visited.
Analysis
- Time Complexity:
O(n) - Auxiliary Space Complexity:
O(1)
Implementation
C++
/* This is the ListNode class definition
class ListNode {
public:
int data;
ListNode* next;
ListNode(int data) {
this->data = data;
this->next = NULL;
}
};
*/
void printLinkedList (ListNode* head) {
ListNode* currentNode = head;
while (currentNode != NULL) {
cout << currentNode->data << " ";
currentNode = currentNode->next;
}
return;
}Java
/** This is the ListNode class definition
class ListNode {
int data;
ListNode next;
ListNode(int data) {
this.data = data;
this.next = null;
}
}
**/
class Solution {
void printLinkedList (ListNode head) {
ListNode currentNode = head;
while (currentNode != null) {
System.out.print(currentNode.data + " ");
currentNode = currentNode.next;
}
return;
}
}