链表–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;
}

原文链接: https://www.cnblogs.com/strive-sun/p/12673129.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍;

也有高质量的技术群,里面有嵌入式、搜广推等BAT大佬

    链表--insert

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/404941

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年4月25日 下午4:48
下一篇 2023年4月25日 下午4:48

相关推荐