小白求助 关于链表逆序的问题
我是照视频打的代码 前面的运行都成功 最后的逆序运行失败#define _CRT_SECURE_NO_WARNINGS
#include "stdio.h"
#include "stdlib.h"
#include "string.h"
typedef struct Node
{
int data;
struct Node* next;
}SLIST;
//创建链表
SLIST* List_Create();
//遍历链表
int List_Print(SLIST* pHead);
//往x前面插入y
int List_Insert(SLIST* pHead, int x, int y);
//删除结点
int List_Delete(SLIST* pHead, int x);
//销毁链表
int List_Destory(SLIST* pHead);
//链表逆序
int List_Inverse(SLIST* pHead);
void main()
{
SLIST* pHead = NULL;
pHead = List_Create();
List_Print(pHead);
List_Insert(pHead, 4, 199);
List_Print(pHead);
List_Delete(pHead, 6);
List_Print(pHead);
List_Destory(pHead);
List_Inverse(pHead);
List_Print(pHead);
system("pause");
}
SLIST* List_Create()
{
SLIST* pHead = NULL;
SLIST* pCur = NULL;
int num = 0;
while (num != -1)
{
printf("请输入num的值:");
scanf("%d", &num);
if (num == -1)
{
break;
}
SLIST* pM = (SLIST*)malloc(sizeof(SLIST));
if (pM == NULL)
{
return NULL;
}
pM->data = num;
pM->next = NULL;
if (pHead == NULL)
{
pHead = pCur = pM;
}
else
{
pCur->next = pM;
pCur = pM;
}
}
printf("num等于-1,存值结束\n");
return pHead;
}
int List_Print(SLIST* pHead)
{
SLIST* pCur = NULL;
for (pCur = pHead; pCur; pCur = pCur->next)
{
printf("%d ", pCur->data);
}
printf("\n");
return 0;
}
int List_Insert(SLIST* pHead, int x, int y)//链表是单向的,链表的位置保存在前驱结点中
{
SLIST* pFre = pHead;
SLIST* pCur = pHead->next;
SLIST* pM = (SLIST*)malloc(sizeof(SLIST));
if (pM == NULL)
{
return -1;
}
pM->data = y;
pM->next = NULL;
while (pCur)
{
if (pCur->data == x)
{
break;
}
pFre = pCur;
pCur = pCur->next;
}
pM->next = pFre->next;
pFre->next = pM;
return 0;
}
int List_Delete(SLIST* pHead, int x)
{
SLIST* pCur = pHead->next;
SLIST* pFre = pHead;
while (pCur)
{
if (pCur->data == x)
{
break;
}
pFre = pCur;
pCur = pCur->next;
}
if (pCur != NULL)
{
pFre->next = pCur->next;
free(pCur);
}
else
{
printf("不存在该元素\n");
return -1;
}
return 0;
}
int List_Destory(SLIST* pHead)
{
SLIST* tmp = pHead;
while (tmp)
{
tmp = pHead->next;
free(pHead);
pHead = tmp;
}
}
//逆序的时候 需要缓存下一个结点的位置这里是逆序
int List_Inverse(SLIST* pHead)
{
if (pHead == NULL || pHead->next == NULL ||pHead->next->next == NULL)
{
return -1;
}
SLIST* tmp = NULL;
SLIST* pCur = pHead->next;
SLIST* pFre = pHead;
while (pCur)
{
tmp = pCur->next;
pCur->next = pFre;
pFre = pCur;
pCur = tmp;
}
pHead->next->next = NULL;
pHead->next = pFre;
return 0;
}
if (pHead == NULL || pHead->next == NULL ||pHead->next->next == NULL)
我觉得这句话有问题,这里应该是判断单链表为空链表或者单链表只有一个元素。但是pHead->next->next是有问题的。pHead->next指向的是下一个元素而不是下一个节点。 哦哦
页:
[1]