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


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;
}

这是我的代码,出于某种原因,只打印第一个节点,然后结束。我哪里做错了?另外,从低到高对链表进行排序背后的思想是什么?

基本上,你要做的是:

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);

相关内容

  • 没有找到相关文章

最新更新