[英]Pointer in linked list
我必須在 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++;
}
}
好吧,您的 add 函數正在返回鏈表的新頭。 但是你沒有對返回值做任何事情,所以鏈表的頭部沒有被更新。
代替 add(head),嘗試 head = add(head)。 這會將鏈接列表的頭部更新為新創建的元素。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.