How To Print The Last Three Nodes Of A Linked List?

20 February 2022 - 1 answer

My whole code to try to get the las three nodes of a linked list is: Node class:

package com.company;

public class Node {

public int data;
public Node nextNode;

public Node(int data) {
this.data = data;
this.nextNode = null;
}

public int getData() {
return data;
}
}

package com.company;
public int size;

this.size = 0;
}

Node node = new Node(data);
} else {
while(currentNode.nextNode != null) {
currentNode = currentNode.nextNode;
}
currentNode.nextNode = node;
}
size++;
}

public void printData() {

while(currentNode != null) {
int data = currentNode.getData();
System.out.println(data);
currentNode = currentNode.nextNode;
}
}

public void printLastThree(){
int i = this.size - 3;
while(i <= this.size) {
int data = currentNode.getData();
System.out.println(data);
currentNode = currentNode.nextNode;
i++;
}
}
}

Main class:

package com.company;
public class Main {
public static void main(String[] args) {

ll.printData();
System.out.println();
ll.printLastThree();
}
}

As you can see, in the linked list class I try to print the last three nodes of the linked list with the printLastThree() method, but in console I just get:

1
2
3
4

And I would like to get:

10
11
12

Can you say me what I am doing wrong? I try in printLastThree() method to get the total size of the linked list and substract 3 positions, and then get to the total size of the linked list, but that doesn't work. Thanks.

Once can see from your code that currentNode starts as the head node, and its value gets printed in the first iteration of the loop. This is not what you want.

You'll first have to skip nodes, which do not get printed. You already calculated how many such nodes need to be skipped (this.size - 3), so you only need to add the loop to actually skip that many nodes:

public void printLastThree(){
// First SKIP nodes (not to be printed)
for (int i = size - 3; i > 0; i--) {
currentNode = currentNode.nextNode;
}
// ...and only then start printing
while (currentNode != null) {
int data = currentNode.getData();
System.out.println(data);
currentNode = currentNode.nextNode;
}
}

You can also do it with one loop, and make the printing conditional on the current index:

public void printLastThree(){