打印数据存储在链接列表中

时间:2015-02-13 18:53:53

标签: c++ linked-list

当我为我创建的链接列表调用print函数时,我遇到了一些问题。我创建了三个列表对象,在其中存储了1,2,3,然后当我运行程序时,打印出数据,然后是十六进制数字。这是输出:

10x47e864
20x47e864
30x47e864

Process returned 0 (0x0)   execution time : 0.026 s
Press any key to continue.

这是.h文件:

#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

这是.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
    }
}

谢谢大家的帮助!

1 个答案:

答案 0 :(得分:0)

cout中的PrintList()语句不正确,从此行中删除第二个cout,即更改

cout<<curr->data<<cout<<endl;

cout <<  curr->data << endl;