This exercise focuses on traversing a linked list. You are given a pointer to the node of a linked list. The task is to print the of each node, one per line. If the head pointer is , indicating the list is empty, nothing should be printed.
Function Description
Complete the printLinkedList function with the following parameter(s):
SinglyLinkedListNode Head: a reference to the head of the list
Print
For each node, print its data value on a new line (console.log in Javascript).
Input Format
The first line of input contains , the number of elements in the linked list.
The next lines contain one element each, the values for each node.
Note: Do not read any input from stdin/console. Complete the printLinkedList function in the editor below.
Constraints
, where is the element of the linked list.
Sample Input
STDIN Function
----- --------
2 n = 2
16 first data value = 16
13 second data value = 13
Sample Output
16
13
Explanation
There are two elements in the linked list. They are represented as 16 -> 13 -> NULL. So, the function should print 16 and 13 each on a new line.
static void printLinkedList(SinglyLinkedListNode head) {
if (head == null) return;
else {
System.out.println(head.data);
printLinkedList(head.next);
}
}
1) Linked List 구현 방법
static class SinglyLinkedListNode {
public int data;
public SinglyLinkedListNode next;
public SinglyLinkedListNode(int nodeData) {
this.data = nodeData;
this.next = null;
}
}
static class SinglyLinkedList {
public SinglyLinkedListNode head;
public SinglyLinkedListNode tail;
public SinglyLinkedList() {
this.head = null;
this.tail = null;
}
public void insertNode(int nodeData) {
SinglyLinkedListNode node = new SinglyLinkedListNode(nodeData);
if (this.head == null) {
this.head = node;
} else {
this.tail.next = node;
}
this.tail = node;
}