链表--insert

分别是使用了二级指针和一级指针的两种方法,最后会按插入的顺序依次打印1,2,3,4

主要区别在于,使用二级指针,可以在main函数里直接用一个空的Node指针,而一级指针是在main函数里面先添加了一个空的头结点

因为二级指针是传的指针的指针,所以main函数里直接用Node *head  = NULL后 , 传&head是没有问题的,因为传的是head的指针的指针,所以在Insert函数里会修改指针的地址。

而一级指针就不行,如果传进去head的指针之后,最终传回来的还是一开始的结果为NULL的指针地址,相当于是以前常看到的,创建一个函数来交换两个变量,可以通过传指针来修改指针所指向的变量。而我们传的head的指针,相当于这个变量,在函数里无论怎么修改这个指针,最终之前传进去的指针并不会变。

也就是说,如果你要在函数里(比如下面insert函数)改变指针的地址,那就传指针的指针来修改指针的地址。

使用二级指针---insert 

#include <iostream>

using namespace std;

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

void Insert(Node** h, int new_data)
{
    cout << h << endl;
    cout << *h << endl;
    Node* newnode = new Node();

    Node* last = *h;
    

    newnode->data = new_data;
    newnode->next = NULL;

    if (*h == NULL)
    {
        *h = newnode;

        return;
    }


    while (last->next != NULL)
    {
        cout << last << endl;
        last = last->next;
        cout << last << endl;
    }

    last->next = newnode;
    cout << last << endl;
    cout << h << endl;
    cout << *h << endl;
    cout << last->next << endl;
    return;
}


void print(Node* h)
{
    if (h == NULL)
    {
        return;
    }

    while (h != NULL)
    {
        cout << h->data <<" ";
        h = h->next;
    }

    return;
}

int main()
{
    Node* head = NULL;

    Insert(&head, 1);
    Insert(&head, 2);
    Insert(&head, 3);
    Insert(&head, 4);

    print(head);

    return 0;

}

使用一级指针--insert

#include <iostream>

using namespace std;

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



void insert(Node* h, int new_data)
{
    Node* newnode = new Node();
    newnode->data = new_data;
    newnode->next = NULL;

    Node* last = h;

    while (last->next != NULL)
    {
        last = last->next;
    }

    last->next = newnode;
}

void print(Node* h)
{
    if (h == NULL)
    {
        return;
    }

    while (h != NULL)
    {
        cout << h->data <<" ";
        h = h->next;
    }

    return;
}

int main()
{
    Node* head = new Node();
    head->data = 1;
   
    insert(head, 2);
    insert(head, 3);
    insert(head, 4);

    print(head);

    return 0;
}
posted @ 2020-04-10 14:07  strive-sun  阅读(675)  评论(0编辑  收藏  举报