Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

C++ Why does my code output infinitely after i input? #include using namespace std; struct ListNode { char name; ListNode *up; ListNode *down; ListNode *left;

C++ Why does my code output infinitely after i input?

#include using namespace std; struct ListNode { char name; ListNode *up; ListNode *down; ListNode *left; ListNode *right; // Constructor to initialize the node ListNode(char nodeName) : name(nodeName), up(NULL), down(NULL), left(NULL), right(NULL) {} }; void findPath(ListNode *currentNode, char destinationNode) { if (currentNode == NULL || currentNode->name == destinationNode) { if (currentNode != NULL) { cout << currentNode->name << " ends" << endl; } return; } cout << "Going "; if (currentNode->left != NULL) { cout << "left to "; findPath(currentNode->left, destinationNode); } if (currentNode->down != NULL) { cout << "down to "; findPath(currentNode->down, destinationNode); } if (currentNode->up != NULL) { cout << "up to "; findPath(currentNode->up, destinationNode); } if (currentNode->right != NULL) { cout << "right to "; findPath(currentNode->right, destinationNode); } } int main() { // Creating nodes and establishing connections ListNode *A = new ListNode('A'); ListNode *B = new ListNode('B'); ListNode *C = new ListNode('C'); ListNode *D = new ListNode('D'); ListNode *E = new ListNode('E'); ListNode *F = new ListNode('F'); ListNode *G = new ListNode('G'); ListNode *H = new ListNode('H'); ListNode *I = new ListNode('I'); A->right = B; B->left = A; B->down = D; B->up = A; C->up = F; D->up = B; D->down = E; E->up = D; F->down = C; G->up = H; H->down = G; H->right = I; I->up = C; // The 2D array representing the grid ListNode *map[3][3] = {{A, B, C}, {D, E, F}, {G, H, I}}; char startNode, destinationNode; cout << "Please enter the starting node: "; cin >> startNode; cout << "Please enter the destination node: "; cin >> destinationNode; // Find and display the path findPath(map[0][0], destinationNode); // Deallocate memory for (int i = 0; i < 3; ++i) { for (int j = 0; j < 3; ++j) { delete map[i][j]; } } return 0; }

Step by Step Solution

There are 3 Steps involved in it

Step: 1

blur-text-image

Get Instant Access to Expert-Tailored Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image

Step: 3

blur-text-image

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Recommended Textbook for

Practical Issues In Database Management A Refernce For The Thinking Practitioner

Authors: Fabian Pascal

1st Edition

0201485559, 978-0201485554

More Books

Students also viewed these Databases questions