122k views
1 vote
Write in c++ recursively display all nodes except the last node
in a linked list

User Catharz
by
7.3k points

1 Answer

1 vote

Final answer:

In C++, you can recursively display all nodes except the last node in a linked list by defining a recursive function.

Step-by-step explanation:

In C++, you can recursively display all nodes except the last node in a linked list by defining a recursive function. Here is an example:

#include

class Node {
public:
int data;
Node* next;
};

void displayExceptLast(Node* node) {
if (node == NULL || node->next == NULL) {
return;
}
cout << node->data << ", ";
displayExceptLast(node->next);
}

int main() {
Node* head = new Node();
Node* second = new Node();
Node* third = new Node();

head->data = 1;
head->next = second;
second->data = 2;
second->next = third;
third->data = 3;
third->next = NULL;

displayExceptLast(head);
return 0;
}

This code defines a Node class and a recursive function displayExceptLast. The function checks if the current node is NULL or if it has no next node, which means it is the last node. If not, it prints the current node's data and calls itself recursively with the next node as the argument.

User Emil Haas
by
8.2k points