I have been trying to implement function to add element at the end of an linked list but it is not working.
I tried to debug code in code::blocks and found that "h->next = newNode;" is not assigning the value.
#include <iostream>
using namespace std;
class Node {
public:
int data;
Node * next;
};
void pushend(Node * h, int newData) {
Node * newNode;
newNode = new Node;
newNode - > data = newData;
newNode - > next = nullptr;
while (h != nullptr) {
if (h - > next == nullptr) {
h - > next = newNode;
break;
}
h = h - > next;
}
}
void printlist(Node * h) {
while (h - > next != nullptr) { //or h!=0
cout << h - > data << endl;
h = h - > next;
}
}
int main() {
Node * head;
Node * second;
Node * third;
head = new Node;
second = new Node;
third = new Node;
head - > data = 1;
head - > next = second;
second - > data = 2;
second - > next = third;
third - > data = 3;
third - > next = nullptr;
int newData = 4;
pushend(head, newData);
printlist(head);
}
Aucun commentaire:
Enregistrer un commentaire