我正在嘗試自學鏈表,因此我設法撰寫了一小段代碼來創建三個鏈接節點,然后將它們列印出來。除了它只列印出第一個元素,我不明白為什么不列印出另外兩個。
另外,我很確定我應該在使用 malloc 時釋放記憶體?但我不知道在哪里?
無論如何,我做錯了什么?這是代碼...
我知道那里有類似的答案,但我已經檢查過了,并且更喜歡針對我的具體情況的答案,因為否則我不會得到它......
#include<stdio.h>
#include <stdlib.h>
struct Node
{
int data;
struct Node *next;
};
void printList(struct Node *ptr);
int main(void)
{
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 = 10;
head->next = second;
second->data = 20;
head->next = third;
third->data = 30;
head->next = NULL;
printList(head);
}
void printList(struct Node *ptr)
{
struct Node *listPtr;
listPtr = ptr;
int count = 1;
if (listPtr == NULL)
{
printf("No elements in list.\n");
return;
}
while (listPtr!=NULL)
{
printf("element %d = %d\n",count,listPtr->data);
listPtr = listPtr->next;
count ;
}
}
我查看了類似的代碼示例,它們(至少其中幾個)看起來與我的相似,所以我真的不知道我做錯了什么......
uj5u.com熱心網友回復:
printList()很好。問題是如何初始化main(). @ShlomiAgiv 給了你一個答案,這是另一個:
int main(void) {
struct Node nodes[] = {
{ 10, nodes 1 },
{ 20, nodes 2 },
{ 30, NULL }
};
printList(nodes);
}
回傳:
element 1 = 10
element 2 = 20
element 3 = 30
這是appendList()動態分配每個節點的。它回傳正在創建的第一個節點(如果它是一個新串列,則它是串列的根),并將*tail指標更新為最后一個節點:
struct Node *appendList(struct Node **tail, size_t len, int data[len]) {
struct Node *root = NULL;
for(size_t i = 0; i < len; i ) {
struct Node *n = malloc(sizeof *n);
if(!root)
root = n;
if(!n) {
// freeList(root);
return NULL;
}
n->data = data[i];
if(*tail) {
(*tail)->next = n;
}
*tail = n;
}
(*tail)->next = NULL;
return root;
}
int main(void) {
struct Node *tail = NULL;
struct Node *root = appendList(&tail, 3, (int []) {10, 20, 30});
appendList(&tail, 1, (int []) { 40 });
printList(root);
// freeList(root);
}
它將列印:
element 1 = 10
element 2 = 20
element 3 = 30
element 4 = 40
uj5u.com熱心網友回復:
寫這個而不是你所做的:
second->data = 20; //same
second->next = third;
third->data = 30; //same
third->next = NULL;
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/534166.html
標籤:C指针链表分配节点
