我有一個程序要求輸入一個數字。然後,如果我接下來輸入「0」,它將在前面插入數字/項目(列表頂部)。如果我接下來輸入「1」,它將在後面(列表的底部)插入號碼/項目。需要幫助解決C指針鏈表分配問題
我遇到的問題是讓後端代碼工作。我試圖從邏輯上理解我的想法,但這看起來不太合適。 links.h文件具有Item的定義。它包含數據和下一個(指向下一個對象的指針)。
這是我到目前爲止的代碼。
我負責編寫insertFront()和insertRear()函數。前面已經在工作了。據說在else語句後只需要2行代碼。
#include "links.h"
#include <stdio.h>
#include <stdlib.h>
int main (void) {
Item *head, *tail;
Item *newItem;
int data, insert;
/* Link the empty list */
head = tail = NULL;
/* Prompt the user for new data to be inserted into the list */
while (1) {
/* Get the data value */
printf ("Enter the positive integer that you want to insert into list (-1 to end): ");
fflush(stdout);
if (scanf ("%d",&data) != 1) {
/* If it isn't valid input, throw away the rest of the line of input */
while (getchar() != '\n') { }
fprintf(stderr, "Invalid data found. Try again.\n");
continue;
}
/* A negative value terminates the list entry */
if (data < 0) break;
printf("Enter a 0 to insert data at the beginning or 1 to insert at the end: ");
fflush(stdout);
if (scanf ("%d",&insert) != 1 || insert < 0 || insert > 1) {
/* If it isn't valid, throw away the rest of the line of input */
while (getchar() != '\n') { }
fprintf(stderr, "Must be zero or one! Try insertion again.\n");
continue;
}
if ((newItem = malloc(sizeof(Item))) == NULL) {
perror ("Unable to allocate memory for new item");
return EXIT_FAILURE;
}
newItem->next = NULL;
newItem->data = data;
if (insert == 0) {
insertFront (newItem, &head, &tail);
} else {
insertRear (newItem, &head, &tail);
}
/* Print the list in forward order */
printf("List in forward order:\n");
printList (head);
}
}
/* Insert the item into front of the list */
void insertFront (Item *item, Item **headptr, Item **tailptr) {
if(*headptr == NULL) {
*headptr = item; // item is the address
*tailptr = item;
} else {
item->next = *headptr;
*headptr = item;
}
}
void insertRear (Item *item, Item **headptr, Item **tailptr) {
if(*tailptr == NULL) {
*tailptr = item;
*headptr = item;
} else {
item->next = *tailptr;
*tailptr = item;
}
}
/* Print the list in forward order */
void printList (Item *head) {
Item *current = head;
while (current != NULL) {
printf ("%d\n", current->data);
current = current->next;
}
}
那就是我以爲我自己。但是編譯器在使用* tailptr-> next = item時給了我錯誤;所以我用了等價的:(** tailptr).next = item;它的工作!謝謝 – user1930558