Dec 7, 2016 at 11:46pm Dec 7, 2016 at 11:46pm UTC
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72
/*
Create a singly linked list which contains 3 nodes. The user is requested to provide a single value which will
become the "elem" value for the node. Then repeat the process 2 more times. After you have completed the list,
read thru the list from the beginning and print each node.
*/
#include <iostream>
#include <string>
using namespace std;
struct node {
int key;
string name;
node *next;
};
node *firstNode = nullptr ;
void addFrontNode (int k, string na) {
node *n = new node;
n->key = k;
n->name = na;
n->next = firstNode;
firstNode = n;
}
void addNewNode (int k, string na, int location) {
node *n = new node;
n->key = k;
n->name = na;
node *visitor = firstNode;
node *next = nullptr ;
while (visitor != nullptr ) {
if (visitor->key == location) {
next = visitor->next;
visitor->next = n;
n->next = next;
break ;
}
else
visitor = visitor->next;
}
}
void addLastNode(int k, string na) {
node *n = new node;
n->key = k;
n->name = na;
node *visitor = firstNode;
node *next = nullptr ;
while (visitor != nullptr ) {
next = visitor;
visitor = visitor->next;
}
next->next = n;
}
void displayNode() {
node *visitor = firstNode;
while (visitor != nullptr ) {
cout << "(" << visitor->key << ", " << visitor->name << ")" ;
if (visitor->next != nullptr )
cout << "--->" ;
visitor = visitor->next;
}
cout << endl;
}
int main()
{
addFrontNode(100, "John" );
addFrontNode(200, "James" );
addFrontNode(150, "Jane" );
displayNode();
return 0;
}
The compiler says that on line 22 nullptr was not declared in the scope. I don't know how to fix this
Last edited on Dec 7, 2016 at 11:52pm Dec 7, 2016 at 11:52pm UTC
Dec 8, 2016 at 11:39am Dec 8, 2016 at 11:39am UTC
nullptr
needs c++11. Either you change the compiler switch or define it yourself like #define nullptr 0
Dec 8, 2016 at 12:03pm Dec 8, 2016 at 12:03pm UTC
Probably not my business, but adding node *firstNode = nullptr ;
as a global variable to be used from within functions is a bad practice. It might not seem like a problem here but if you're learning to code then it's best to use good programming practices from the beginning.
Last edited on Dec 8, 2016 at 12:04pm Dec 8, 2016 at 12:04pm UTC