我僅限于使用一種在給定節點之后插入新節點并實作鏈表的方法。我的輸出中出現了垃圾值。我不清楚如何解決這個問題。提前感謝任何幫助。
#include<stdio.h>
#include<stdlib.h>
struct Node{
int data;
struct Node *next;
};
void insertAfter(struct Node *prevNode,int newData){
if(prevNode == NULL){
printf("the given previous node cannot be NULL");
return;
}
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->data = newData;
newNode->next = prevNode->next;
prevNode->next = newNode;
}
void printList(struct Node *head){
while(head!=NULL){
printf(" %d ", head->data);
head = head->next;
}
}
int main()
{
struct Node* head = NULL;
struct Node* second = NULL;
struct Node* third = NULL;
head = (struct Node*)malloc(sizeof(struct Node));
second = (struct Node*)malloc(sizeof(struct Node));
third = (struct Node*)malloc(sizeof(struct Node));
head->data = 9;
head->next = second;
insertAfter(head->next, 8);
third->data = 10;
third->next = NULL;
printf("\n Created Linked list is: ");
printList(head);
return 0;
}
生成的輸出:9 0 8 預期輸出:9 8 10
uj5u.com熱心網友回復:
此代碼段
struct Node* head = NULL;
struct Node* second = NULL;
struct Node* third = NULL;
head = (struct Node*)malloc(sizeof(struct Node));
second = (struct Node*)malloc(sizeof(struct Node));
third = (struct Node*)malloc(sizeof(struct Node));
head->data = 9;
head->next = second;
insertAfter(head->next, 8);
third->data = 10;
third->next = NULL;
是錯的。指標指向的節點third不包含在串列中,并且指標指向的節點second具有未初始化的資料成員。
至少你應該寫例如
struct Node* head = NULL;
struct Node* second = NULL;
struct Node* third = NULL;
head = (struct Node*)malloc(sizeof(struct Node));
second = (struct Node*)malloc(sizeof(struct Node));
third = (struct Node*)malloc(sizeof(struct Node));
head->data = 9;
head->next = second;
second->data = 10;
second->next = third;
third->data = 11;
third->next = NULL;
insertAfter(head->next, 8);
uj5u.com熱心網友回復:
head->next = second;
這里second包含垃圾。你要
head->next = NULL;
然后second不需要third變數。相反,您需要呼叫insertAfter兩次才能插入 8 和 10。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/523660.html
標籤:C数据结构结构单链表
