有人能告訴我爲什麼我的代碼只打印鏈表中的最後一個值,不太擅長編碼,所以幫助會有用!有人可以告訴我爲什麼我的鏈表無法正確顯示嗎? (C編程)
這是代碼:
#include <stdio.h>
#include <stdlib.h>
typedef struct node {
int data; //element
struct node * next; //address of next node
} node_t;
node_t * create(int n);
void display(node_t *head);
int main(int argc, char *argv[]) {
int n=0;
node_t * HEAD=NULL;
printf("Enter number of nodes: ");
scanf("%d",&n);
HEAD=create(n);
display(HEAD);
return 0;
}
node_t * create(int n) {
node_t * head=NULL;
node_t * temp=NULL;
node_t * p=NULL;
int i;
for (i=0; i<n; i++) { // this is just reading the nodes
temp=(node_t*)malloc(sizeof(node_t));
printf("\n Enter the data for node num %d: ",i+1);
scanf("%d",&(temp->data));
temp->next=NULL;
}
if (head==NULL) { //if list is item
head = temp;
} else { // this is linking the items.
p =head;
while (p->next !=NULL) {
p=p->next;
p->next=temp;
}
}
return head;
}
void display(node_t *head) {
node_t *p = head;
while (p !=NULL) {
printf("\n%d->",p->data);
p=p->next;
}
}
這是輸出:
輸入節點的數量:3
輸入節點NUM 1中的數據:2
輸入數據節點號碼2:4
輸入數據節點號碼3:1
1->
內存泄漏....你自己寫了這段代碼? – coderredoc
一種,遵循YouTube教程大聲笑..哦,天哪我不是很好,malloc和東西。我該如何解決? – Rita
你設置了多少次'p-> next = temp;'?當你做什麼時,每個'p-> next'會發生什麼? –