C语言链表反转代码错误分析及解决方案
#include <stdio.h> #include <stdlib.h>
typedef struct Linklist { int data; struct Linklist* next; } LNode;
int num;
LNode *creatLinklist() { LNode head = (LNode)malloc(sizeof(LNode)); return head; }
LNode* addNode(LNode *preNode, int currentData) { LNode currentNode = (LNode)malloc(sizeof(LNode)); currentNode->data = currentData; preNode->next = currentNode; currentNode->next = NULL; // 初始化 next 成员 return currentNode; }
void initLinklist(LNode *headNode) { scanf('%d', &num); int tmpValue; for (int i = 0; i < num; i++) { scanf('%d', &tmpValue); printf('%d ', tmpValue); headNode = addNode(headNode, tmpValue); } }
void outPrint(LNode *headNode) { LNode *releaseNode; headNode = headNode->next; while (headNode != NULL) { printf('%d', headNode->data); releaseNode = headNode; headNode = headNode->next; free(releaseNode); if (headNode != NULL) printf(' '); } }
void reverse(LNode *head) { LNode *nextOne, *current, *pre; pre = head->next; current = head->next->next; nextOne = current->next; while (current != NULL) { current->next = pre; if (nextOne != NULL) { pre = current; current = nextOne; nextOne = nextOne->next; } else { break; } } }
int main() { int T; scanf('%d\n', &T); LNode *head = creatLinklist(); while (T--) { initLinklist(head); reverse(head); // outPrint(head); printf('\n'); }
return 0;
}
// 该段代码报错是因为在addNode函数中,没有给currentNode的next成员进行初始化,导致出现了未知的指针指向,进而导致了错误的内存访问。 // 应该在addNode函数中添加以下代码来初始化next成员:
// currentNode->next = NULL;
原文地址: https://www.cveoy.top/t/topic/paBJ 著作权归作者所有。请勿转载和采集!