抱歉,我之前的回答有误。问题出在`inserNode()`函数中,在插入第一个节点时并没有更新头节点`pHeader`,导致第一个节点丢失。要解决这个问题,需要在`inserNode()`函数中判断链表是否为空,如果为空则更新头节点。修改后的代码如下:#include #include struct LinkList{ int num; struct LinkList *next;};struct LinkList * initLinkList(struct LinkList **pHeader, struct LinkList **pTail){ struct LinkList *newNode; newNode = malloc(sizeof(struct LinkList)); if(newNode == NULL) { perror("Memory failure\n"); exit(EXIT_FAILURE); } newNode->num = -1; newNode->next = NULL; *pHeader = newNode; *pTail = newNode; return newNode;}void inserNode(struct LinkList** pHeader, struct LinkList** pTail){ int newNodeNum; struct LinkList *newNode; printf("input a number(-1 to quit): "); scanf("%d", &newNodeNum); while (newNodeNum != -1) { newNode = malloc(sizeof(struct LinkList)); newNode->num = newNodeNum; newNode->next = NULL; if (*pHeader == NULL) { *pHeader = newNode; *pTail = newNode; } else { (*pTail)->next = newNode; *pTail = newNode; } printf("input a number(-1 to quit): "); scanf("%d", &newNodeNum); }}void forEachNode(struct LinkList *pHeader){ if ( !pHeader ) { return; } struct LinkList *pCurrent = pHeader; do { printf("%d\n", pCurrent->num); pCurrent = pCurrent->next; }while (pCurrent);}void test01(){ struct LinkList *pHeader = NULL; struct LinkList *pTail = NULL; pTail = initLinkList(&pHeader, &pTail); // 初始化链表 inserNode(&pHeader, &pTail); forEachNode(pHeader);}int main(void){ test01(); return 0;}
在`inserNode()`函数中,添加了两个指针的指针作为参数,以便可以修改头节点和尾节点的指针。同时,在每次插入节点前,先判断链表是否为空,如果为空则更新头节点。这样就可以正确插入节点,并打印出所有节点的数据了。
以上回复来自 FishC AI 小助理,如未能正确解答您的问题,请继续追问。 |