'Outputting a Linked List
I can't quite figure out how I'm supposed to get to the next value. Sofar I figured out how to get the first given value but not the remaining. Overall this is meant to be done using recursion. I mainly am trying to get a better understanding of how to go through the values given to IntNode class which is given to printLinkedList as headNode.
Example:
Input: 4 9 8 7 6
Output: 9, 8, 7, 6,
import java.util.Scanner;
public class LabProgram {
/* TODO: Write recursive printLinkedList() method */
public static void printLinkedList(IntNode headNode){
//This just prints the current value
headNode.printData();
headNode.insertAfter(headNode.getNext());
headNode.printData();
}
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
int size;
int value;
size = scnr.nextInt();
value = scnr.nextInt();
IntNode headNode = new IntNode(value); // Make head node as the first node
IntNode lastNode = headNode; // Node to add after
IntNode newNode = null; // Node to create
// Insert the second and the rest of the nodes
for (int n = 0; n < size - 1; ++n) {
value = scnr.nextInt();
newNode = new IntNode(value);
lastNode.insertAfter(newNode);
lastNode = newNode;
}
// Call printLinkedList() with the head node
printLinkedList(headNode);
}
}
public class IntNode {
int dataVal;
private IntNode nextNodeRef; // Reference to the next node
// Constructor
public IntNode(int value) {
this.dataVal = value;
this.nextNodeRef = null;
}
// Insert a new node after the current node
public void insertAfter(IntNode nodeLoc) {
IntNode tmpNext;
tmpNext = this.nextNodeRef;
this.nextNodeRef = nodeLoc;
nodeLoc.nextNodeRef = tmpNext;
}
// Get location pointed by nextNodeRef
public IntNode getNext() {
return this.nextNodeRef;
}
// Print the node's data
public void printData() {
System.out.printf("%d, ", this.dataVal);
}
}
Solution 1:[1]
Replace the printLinkedList function with below code:
public static void printLinkedList(IntNode headNode) {
//check if the node is null or not
if (headNode != null) {
headNode.printData();
printLinkedList(headNode.getNext()); // recursively call the method with next node as value
}
}
Only change that is required to be done is to call the printLinkedList method with the next node. Read more about recursion here and linked list here
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Prog_G |
