我必須在 C 中創建一個雙向鏈表。這個串列應該像堆疊一樣作業,就像我需要在開頭添加新元素一樣。我創建了一個頭,它有 NULL。我將它用于我的串列為空的情況。但是當第二次迭代運行時,我的頭仍然是 NULL。這是我的代碼:
#include <stdio.h>
#define _CRT_SECURE_NO_WARNINGS
#include <stdlib.h>
#define LEN 1000
typedef struct list {
char* string;
struct list* prev, * next;
}LL;
LL* add(LL* head) {
LL* temp = malloc(sizeof(LL));
char buf[LEN];
if (gets(buf) == '0')
return 0;
temp->string= (char*)malloc(strlen(buf) 1);
strcpy(temp->string, buf);
if (head == NULL) {
temp->next = NULL;
temp->prev = NULL;
head = temp;
return head;
}
temp->prev = NULL;
temp->next = head;
head->prev = temp;
head = temp;
return head;
}
int main() {
LL* head = NULL;
int i = 0;
while (i != 3) {
add(head);
i ;
}
}
uj5u.com熱心網友回復:
好吧,您的 add 函式正在回傳鏈表的新頭。但是你沒有對回傳值做任何事情,所以鏈表的頭部沒有被更新。
代替 add(head),嘗試 head = add(head)。這會將鏈接串列的頭部更新為新創建的元素。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/487155.html
上一篇:如何回傳二維陣列?
