• 图示指针传值操作


    传值操作

    #include <iostream>
    using namespace std;
    
    struct ListNode
    {
        int m_nValue;
        ListNode* m_pNext;
    };
    
    void createList(ListNode *head)
    {
        head = new(ListNode);
        head->m_nValue = 1;
        head->m_pNext = NULL;
    }
    void deleteList(ListNode *p)
    {
        ListNode *next = NULL;
        while(p != NULL)
        {
            cout << p->m_nValue << endl;
            next = p->m_pNext;
            delete p;
            p = NULL;
            p = next;
        }
    }
    
    int main()
    {
        ListNode *head = NULL;
        createList(head);
        cout << head << endl;
        deleteList(head);
    }
        

    结果

    0

    分析

    主函数中的指针head为传值调用,传到函数并没有改变主函数中的值,图示

    改进的措施就是引用传值,直接操纵原指针。

    改进1

    #include <iostream>
    using namespace std;
    
    struct ListNode
    {
        int m_nValue;
        ListNode* m_pNext;
    };
    
    void createList(ListNode *&head)
    {
        head = new(ListNode);
        head->m_nValue = 1;
        head->m_pNext = NULL;
    }
    void deleteList(ListNode *p)
    {
        ListNode *next = NULL;
        while(p != NULL)
        {
            cout << p->m_nValue << endl;
            next = p->m_pNext;
            delete p;
            p = NULL;
            p = next;
        }
    }
    
    int main()
    {
        ListNode *head = NULL;
        createList(head);
        cout << head << endl;
        deleteList(head);
    }
        

    改进2

    #include <iostream>
    using namespace std;
    
    struct ListNode
    {
        int m_nValue;
        ListNode* m_pNext;
    };
    
    void createList(ListNode **head)
    {
        *head = new(ListNode);
        (*head)->m_nValue = 1;
        (*head)->m_pNext = NULL;
    }
    void deleteList(ListNode *p)
    {
        ListNode *next = NULL;
        while(p != NULL)
        {
            cout << p->m_nValue << endl;
            next = p->m_pNext;
            delete p;
            p = NULL;
            p = next;
        }
    }
    
    int main()
    {
        ListNode *head = NULL;
        createList(&head);
        cout << head << endl;
        deleteList(head);
    }
        

    细节:->优先级高于*

  • 相关阅读:
    python argparse sys.argv
    python __all__
    一些方便系统诊断的bash函数
    yarn集群客户端gateway常用限制
    xcrun: error: invalid active developer path (/Library/Developer/CommandLineTools), missing xcrun
    Hadoop fs -put bandwidth 暴力版
    PYTHON SOCKET编程简介
    java实现点选汉字验证码(转)
    springboot配置log4j
    vue文字跑马灯效果
  • 原文地址:https://www.cnblogs.com/kaituorensheng/p/3603611.html
Copyright © 2020-2023  润新知