反转链表,关于指针的一点知识和九度oj1518

题意 求反转链表

题目链接

所犯的错误

  • 这道题尽管是道水题,但写程序的时候指针出现了一点错误,导致调了一阵子都不知道哪错了先把代码放上来
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;

struct ListNode
{
    int val;
    ListNode *next;
};

ListNode* CreateListNode(int val)
{
    ListNode *pNode = new ListNode();
    pNode->val = val;
    pNode->next = NULL;
    return pNode;
}

void DestoryList(ListNode *pHead)
{
    ListNode *pNode = pHead;
    while(pHead != NULL)
    {
        pNode = pHead;
        pHead = pHead->next;
        delete pNode;
    }
}

ListNode* ReverseList(ListNode *pHead)
{
    ListNode *ReverseHead = NULL;
    ListNode *pNode = pHead;
    ListNode *pPrev = NULL;

    while(pNode != NULL)
    {
        ListNode *pNext = pNode->next;

        if(pNext == NULL)
            ReverseHead = pNode;

        pNode->next = pPrev;

        pPrev = pNode;
        pNode = pNext;
    }

    return ReverseHead;
}

void PrintList(ListNode *pHead)
{
    ListNode *pNode = pHead;
    while(pNode != NULL)
    {
        printf("%d", pNode->val);
        if(pNode->next != NULL)
            printf(" ");
        pNode = pNode->next;
    }
    printf("\n");
}

int main()
{
    int n, val;
    while(~scanf("%d", &n))
    {
        if(n == 0)
        {
            printf("NULL\n");
            continue;
        }
        ListNode *pHead, *pNode;
        for(int i = 0; i < n; i++)
        {
            scanf("%d", &val);
            if(i == 0)
            {
                pHead = CreateListNode(val);
                pNode = pHead;
            }
            else
            {
                pNode->next = CreateListNode(val);
                pNode = pNode->next;
            }
        }
        pHead = ReverseList(pHead);
        PrintList(pHead);
        DestoryList(pHead);
    }
    return 0;
}

上面是ac的代码,当时我的代码的ReverseList函数本来是void,想直接通过传递head指针在里面函数修改head指针,但是不能完成
也就是想完成如下代码的功能

#include <cstdio>

void f(int *a)
{
    int *b = new int[10];
    for(int i = 0; i < 5; i++)
        b[i] = 100;
    a = b;
}

int main()
{
    int *a = new int[10];
    for(int i = 0; i < 5; i++)
        a[i] = i;
    f(a);
    for(int i = 0; i < 5; i++)
        printf("%d ", a[i]);
    return 0;
}

通过函数来把指针a的地址修改掉,事实上这是行不通的,要写成下面才行

#include <cstdio>

void f(int *(&a))
{
    int *b = new int[10];
    for(int i = 0; i < 5; i++)
        b[i] = 100;
    a = b;
}

int main()
{
    int *a = new int[10];
    for(int i = 0; i < 5; i++)
        a[i] = i;
    f(a);
    for(int i = 0; i < 5; i++)
        printf("%d ", a[i]);
    return 0;
}

也就是说单纯地把a的地址传过去,然后修改a的地址,这样做是不行的,这样只能修改a数组里面的值,必须把指针a的指针地址传过去进行修改

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值