在创建单链表时正确设置指针的问题

时间:2013-03-11 23:46:56

标签: c++ pointers linked-list singly-linked-list

struct Number_Node
{
    int number;
    struct Number_Node* next_number;
};

int counter=0;

int main()
{
    int input=0;
    Number_Node* n;
    Number_Node* h;
    Number_Node* t;
    do
    {
        cout << "Enter Number: ";
        cin >> input;
        n = new Number_Node;
        n->number=input;
        t=n;
        if(counter==0)
        {
            h=n;
            counter++;
        }
        t->next_number=n;
        t=t->next_number;
        n->next_number=NULL;

    }while(input!=-1);

    Number_Node *tmpPtr;
    tmpPtr=h;
    while(tmpPtr!=NULL)
    {
        cout << tmpPtr->number << endl;
        tmpPtr=tmpPtr->next_number;
    }
    return 0;

}

这是我的代码,出于某种原因,只有第一个节点打印,然后事情结束。我在这做错了什么?此外,将链表从低到高排序背后的想法是什么?

1 个答案:

答案 0 :(得分:1)

基本上,你所做的是:

n = new Number_Node;
t=n;
t->next_number=n;
t=t->next_number;
n->next_number=NULL;

等于:

n = new Number_Node;
n->next_number=n;
n=n->next_number;
n->next_number=NULL;

表示您从未正确设置next_number指针。您的代码应如下所示:

Number_Node* newNode  = NULL;
Number_Node* head     = NULL;
Number_Node* lastNode = NULL;
do
{
    // create new node:
    cout << "Enter Number: ";
    cin >> input;
    newNode = new Number_Node;
    newNode->number = input;
    newNode->next_number = NULL;

    // make last node to point to new node:
    if (lastNode)
        lastNode->next_number = newNode;

    // set the head:
    if (counter == 0)
    {
        head = newNode;
        counter++;
    }

    // store the last node:
    lastNode = newNode;

} while (input != -1);