我有一个程序要求输入一个数字。然后,如果我接下来输入“0”,它将在前面(列表顶部)插入数字/项目。如果我接下来输入“1”,它将在后面(列表底部)插入数字/项目。
我遇到的问题是让后面的代码工作。我试图在我的脑海中逻辑地解决这个问题,但它似乎并不正确。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;
}
}