为什么链表的这两种实现方式不同?

时间:2019-09-04 14:07:55

标签: c++

我有两个带有插入和显示功能的LL的两个实现。我插入了2个元素并尝试显示它,但似乎不起作用。

我有一个全局头指针,并将此变量传递给insert和display函数。尽管它不需要传递,因为它是全局的,但我仍然想知道出什么问题了。

struct node{
        int data;
        node* next;
    };

    //global head
    node* head=NULL;

    void dispLL(node* head)
    {
        node* tmp = head;
        while (tmp!=NULL)
        {
            cout<<tmp->data<<" ";
            tmp=tmp->next;
        }
    }

    void insertinLL(node* head,int a)
    {
        node* tmp2=new node;
        tmp2->data=a;
        tmp2->next=NULL;

        if(head == NULL) {
            head=tmp2;
            return;
        }
        else
        {
            struct node* tmp=head;
            while (tmp->next!=NULL)
            {
                tmp=tmp->next;
            }
            tmp->next=tmp2;
        }
    }

    //main
        insertinLL(head,1);
        insertinLL(head,23);
        dispLL(head);

如果删除head参数,或者对于全局head和参数head有2个不同的变量名称,则效果很好。如果head是一个指针并且指向相同的内存位置,那怎么办?

0 个答案:

没有答案