I'm having some issues when I call the print function for a linked list I created. I created three list objects, stored within them the ints 1,2,3 and then when I run the program, the data is printed out, followed by a hexadecimal number. Here is the output:
10x47e864
20x47e864
30x47e864
Process returned 0 (0x0) execution time : 0.026 s
Press any key to continue.
Here is the .h file:
#ifndef LIST_H
#define LIST_H
class List
{
public:
List();
void AddNode(int addData);
void DeleteNode(int delData);
void PrintList();
private:
typedef struct node{
int data;
node* next;
}* nodePtr;
nodePtr head;
nodePtr curr;
nodePtr temp;
};
#endif // LIST_H
Here is the .cpp
#include "List.h"
#include <cstdlib>//for NULL const
#include <iostream>
using namespace std;
int main(){
List li;
li.AddNode(1);
li.AddNode(2);
li.AddNode(3);
li.PrintList();
}
List::List()
{
head = NULL;
curr = NULL;
temp=NULL;
}
void List::AddNode(int addData){
nodePtr n = new node;
n->next=NULL;
n->data=addData;
if(head!=NULL)//if a linked list exists
{
curr = head;
while(curr->next!=NULL){
//while not at end of list
curr=curr->next;//advances ptr until last node in list
}
curr->next=n;//make n point to last node;
}
else{//if list does not exist
head = n;
}
}
void List::DeleteNode(int delData){
nodePtr delPtr = NULL;
temp = head;
curr = head;
while(curr!=NULL && curr->data!= delData){
//to pass through list
temp = curr;
curr = curr->next;//traverse list until delData not found
}
if(curr==NULL)//passed through list, delData int not found
{
cout<<delData<<" was not in list\n";
delete delPtr;
}
else{
delPtr = curr;
curr == curr->next;//patching hole in list
delete delPtr;
cout<<"the value "<<delData<<" was deleted\n";
}
}
void List::PrintList(){
curr = head;
while(curr!=NULL){
cout<<curr->data<<cout<<endl;
curr=curr->next;//adv the curr ptr
}
}
Thank you all for the help!
You have an incorrect cout
statement in the PrintList()
remove the second cout
from this line, ie, change
cout<<curr->data<<cout<<endl;
to
cout << curr->data << endl;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.