I have a program that asks for a number as input. Then if I enter a "0" next, it will insert the number/item at the front (top of the list). If I enter a "1" next, it will insert the number/item at the rear (bottom of list).
The problem I'm having is getting the rear code to work. I'm trying to figure this out logically in my head but it just doesn't seem right. The links.h file has definition for Item. It contains data and a next (pointer to next object).
Here is the code i've got so far.
I was responsible for coding the insertFront() and insertRear() functions. The front is already working. There is supposedly only 2 lines of code needed after the else statment.
#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;
}
}