题意 求反转链表
题目链接
所犯的错误
- 这道题尽管是道水题,但写程序的时候指针出现了一点错误,导致调了一阵子都不知道哪错了先把代码放上来
#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的指针地址传过去进行修改