在特定节点而不是零处插入链表

时间:2019-07-13 07:15:55

标签: c++ c++11

当试图在其他位置插入节点而不是首先没有任何结果时,我在哪里出现错误?插入第二个插入命令时什么都没发生?

class Node
{
public:
    int data;
    class Node *next;
} *first;

int count(class Node *c)
{
    int l = 0;
    while(c)
    {
        l++;
        c=c->next;
    }
    return l;
}

void Insert(int pos,int x)
{
    class Node *t, *p;
    if(pos==0)
    {
        t=new Node;
        t->data=x;
        t->next=first;
        first=t;
    }
    else
    {
        p=first;
        for(int i=0;i<pos&&p;i++)
            p=p->next;
        if(p)
        {
            t=new Node;
            t->data=x;
            t->next=p->next;
            p->next=t;
        }
    }
}

void display(class Node *p)
{
    while(p!=NULL)
    {
        cout<<p->data;
        p=p->next;
    }
}

int main()
{
    first = NULL;
    Insert(0,1);
    Insert(1,2);    // NOT WORKING
    display(first);

    return 0;
}

0 个答案:

没有答案
相关问题