我正在嘗試創建一個沒有動態分配的鏈表,并用 0-8 的數字填充它,然后列印它們,但每次我嘗試它都會給我隨機值。
#include <stdio.h>
struct listNode
{
int value;
struct listNode *next;
};
int main()
{
struct listNode list;
struct listNode *head = &list;
int i;
for (i = 0; i < 9; i )
{
list.value = i;
struct listNode new;
list.next = &new;
list = *(list.next);
}
for (i = 0; i < 9; i )
{
printf("%d, ", (*head).value);
head = (*head).next;
}
return 0;
}
看起來它應該作業,但它沒有,我錯過了什么?
uj5u.com熱心網友回復:
要分配沒有 的節點malloc,也有可能為此目的使用堆疊。這只是作為一個小練習很有趣,但在實際代碼中將是一個壞主意。
這個想法是,每當必須分配一個新節點時,您都??會進行遞回呼叫,然后在該處繼續程式的其余邏輯,而無需從該遞回呼叫中回傳。只有當程式可以退出時,您才會退出遞回。這不是很方便使用,會導致記憶體浪費,因為不僅分配的節點在該堆疊上,而且還有一些其他不再使用的資料。此外,只要從串列中洗掉節點,就不會重復使用空間,除非您還維護一個空閑串列。
再說一次,這不是最佳實踐,應該真正使用堆來進行這種動態分配。我希望這個免責宣告足夠強大,仍然允許我發布實作這個想法的這段代碼:
#include <stdio.h>
struct listNode
{
int value;
struct listNode *next;
};
void printList(struct listNode *head) {
while (head != NULL) {
printf("%d -> ", head->value);
head = head->next;
}
printf("NULL\n");
}
void deleteFromList(struct listNode **headPtr, struct listNode **tailPtr, int value) {
while (*headPtr != NULL && (*headPtr)->value == value) {
*headPtr = (*headPtr)->next;
}
if (*headPtr == NULL) {
*tailPtr = NULL;
return;
}
struct listNode *current = *headPtr;
while (current->next != NULL) {
if (current->next->value == value) {
current->next = current->next->next;
} else {
current = current->next;
}
}
*tailPtr = current;
}
void appendToList(struct listNode **headPtr, struct listNode **tailPtr, struct listNode *new) {
new->next = NULL;
if (*tailPtr != NULL) {
(*tailPtr)->next = new;
} else {
*headPtr = new;
}
*tailPtr = new;
}
// This is the main program's logic, but it gets called recursively whenever a node
// is inserted into the list:
void menu(struct listNode *head, struct listNode *tail) {
struct listNode new;
char choice;
while (1) {
printf("[i]nsert, [d]elete, [p]rint, [e]xit: ");
scanf(" %c", &choice);
switch(choice) {
case 'p':
printList(head);
break;
case 'i':
printf("insert value: ");
scanf(" %d", &new.value);
appendToList(&head, &tail, &new);
menu(head, tail); // Recursion
return;
case 'd':
printf("delete value: ");
scanf(" %d", &new.value);
deleteFromList(&head, &tail, new.value);
break;
case 'e':
return;
}
}
}
int main()
{
menu(NULL, NULL);
return 0;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/448232.html
