图示指针传值操作

传值操作

#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);
}
    

细节:->优先级高于*

posted @ 2014-03-16 17:46  jihite  阅读(564)  评论(0编辑  收藏  举报