So after I got my pointers fixed and everything, the simple command of taking an input from the command line does not work.
Below, I ask how many nodes, then I ask what the value of the first node is.
Then the code just hangs. I have put in test prints to see if its even taking the value and it isnt. But if I remove the line that changes the data of myNode, then it does not hang anymore. Any advice?
//============================================================================
// Name : myLinkedList.cpp
// Author :
// Version :
// Copyright : Your copyright notice
// Description : Hello World in C++, Ansi-style
//============================================================================
myNode is merely a pointer. You need to allocate memory space for it to point to.
Then there is a place to store the data.
I saw in your last post that this is your own project and not home work so...
Try this:
#include <iostream>
usingnamespace std;
class Node
{
public:
Node * pNext;
Node * pPrev;
int data;
};
int main()
{
int nodeNumber;
int thisData;
Node *temp;
Node *head = NULL;// this is needed. It marks end of list
cout<<"How many nodes?";
cin>>nodeNumber;
// create and fill some Nodes
for(int a=0; a<nodeNumber; a++)
{
cout<<"Enter data for " << a << ": ";
cin >> thisData;
temp = new Node;// NOW there is memory to write data to
temp->data = thisData;
temp->pNext = head;// head temporarily 2nd
temp->pPrev = NULL;// temp will be first in list
if(head)head->pPrev = temp;// 2nd node points back to first node
head = temp;// head is always first
}
// display the list contents
temp = head;
while(temp)
{
cout << temp->data << endl;
temp = temp->pNext;
}
// delete the list
while(head)
{
temp = head;
head = head->pNext;
delete temp;
cout << "Node deleted" << endl;
}
cout << endl;
return 0;
}
//Java code
Object obj; //doesn't create an object
obj = new Object(); //create the object, store it in obj
1 2 3 4 5 6
//C++ code
Object *obj; //doesn't create an object
obj = new Object(); //create the object, "new" also returns its location (i.e. a pointer), store the pointer in obj
// optional parentheses, "new Object" does the same thing
Object instance; //although this does create an object, so watch out!
delete obj; //remember C++ does not have automatic garbage collection, deallocate memory (allocated with "new") pointed to by obj