OK, I'm glad you guys are there. Here's my problem, I have been working with Sue Ballew in St. Louis. I have this stack program that is supposed to do a bunch of stuff, push, pop, count, print list, and "delete". I can't get the delete function to work, I took the code right from my King textbook, p 378 but it doesn't work. I've tried different forms for the function, e.g.,
void delete( int input_value)
{
struct node *cur, *prev;
for (cur = first, prev = NULL;
cur != NULL && cur->value != input_value;
prev = cur, cur = cur->next)
;
if (cur == NULL)
printf("value not found\n");
return;
if (prev == NULL)
first = first->next;
else
prev->next = cur->next;
free (cur);
return;
}
but that didn't work either.
I am including the whole program here, if any one can figure out what I am sure is some dumb mistake on my part, I will be very grateful. I am 56 and much too old for this ****.
#include <stdio.h>
#include <stdlib.h>
struct node {
int value;
struct node *next;
};
struct node *first = NULL;
struct node *new_node;
void push( int input_value);
void pop();
/* struct node *delete(struct node *first, int input_value);
*/
void delete(struct node *list, int input_value);
void instructions(void);
void printlist();
main()
{
int input, value, number, lv;
instructions();
printf("?");
scanf("%d", &input);
while (input != 0) {
switch (input) {
case 1:
printf("Enter an integer: ");
scanf("\n%d", &number);
push(number);
printlist();
break;
case 2:
pop();
printlist();
break;
case 3:
printf("Enter value to be removed: ");
scanf("\n%d", &number);
delete(first, number);
printlist();
break;
default:
printf("Invalid choice.\n\n");
break;
}
printf("?");
scanf("%d", &input);
}
printf("End of run.\n");
return 0;
}
void push( int input_value)
{
new_node = malloc(sizeof(struct node));
new_node->value = input_value;
new_node->next = first;
first = new_node;
}
void pop()
{
int lv;
if (first == NULL)
return;
lv = first->value;
printf(" %d returned\n", lv);
first = first->next;
return;
}
void delete(struct node *list,int input_value)
{
struct node *cur, *prev, *q;
for (cur = list, prev = NULL;
cur != NULL && cur->value != input_value;
prev = cur, cur = cur->next)
;
if (cur == NULL)
printf("value not found\n");
return;
if (prev == NULL) {
list = list->next;
printf(" First value removed"); }
else
prev->next = cur->next;
free (cur);
return;
}
void instructions (void)
{
printf("Enter your choice:\n"
" 0 to end program.\n"
" 1 to add a value to the list.\n"
" 2 to remove a value from the list.\n"
" 3 to delete a value from the list.\n");
}
void printlist()
{
struct node *p;
if (first == NULL)
printf("List is empty.\n\n");
else {
printf("The list is:\n");
p = first;
while (p != NULL) {
printf("%d --> ", p->value);
p = p->next;
}
printf("NULL\n\n");
}
}