|
-
October 7th, 2004, 09:06 PM
#1
Method not searching properly...
Code:
#include <stdio.h>
#include <stdlib.h>
struct node
{
int data;
struct node *next;
};
void insert_node(int, struct node**);
struct node * find_node(int, struct node**);
void user_insert(struct node **);
void user_search(struct node **);
int main()
{
struct node *curr;
struct node *list;
int i = 0;
int selection;
curr = list;
for(i = 0; i < 10; i++)
{
insert_node(i, &list);
}
do
{
printf("\n\nPlease enter a selection...\n\n");
printf("-1- See the entire list.\n");
printf("-2- Remove a node from the list.\n");
printf("-3- Insert a node into the list.\n");
printf("-4- Empty the entire list.\n");
printf("-5- Search for a specific node in the list.\n");
printf("-6- Exit.\n");
printf(" - > ");
scanf("%d", &selection);
fflush(stdin);
switch(selection)
{
case 1:
printf("Not yet implemented.\n");
break;
case 2:
printf("Not yet implemented.\n");
break;
case 3:
user_insert(&list);
break;
case 4:
printf("Not yet implemented.\n");
break;
case 5:
user_search(&list);
break;
case 6:
printf("Good bye.\n");
break;
default:
printf("Incorrect input...\n");
}
}
while(selection != 6);
return 0;
}
void insert_node(int value, struct node **list)
{
struct node *new_node = malloc(sizeof(struct node));
new_node -> data = value;
new_node -> next = (*list);
(*list) = new_node;
}
struct node * find_node(int value, struct node **list)
{
struct node *temp = NULL;
int i = 0;
while(!list)
{
if(value == (*(list + i)) -> data)
{
temp = *(list + i);
break;
}
i++;
}
return temp;
}
void user_insert(struct node **list)
{
int insert_value;
printf("Please enter a value that you would like to insert into the list - > ");
scanf("%d", &insert_value);
fflush(stdin);
insert_node(insert_value, list);
}
void user_search(struct node **list)
{
int search_value;
printf("Please enter a value that you would like to look up in the list - > ");
scanf("%d", &search_value);
fflush(stdin);
struct node *search_temp = find_node(search_value, list);
if(search_temp)
{
printf("The value %d has been found in the list.\n", search_value);
}
else
{
printf("The value %d has not been found in the list.\n", search_value);
}
}
I'm using gcc. I'm a newbie to linked lists so I don't understand the idea too well, but I'm trying to learn through examples and attempts.
My problem is that whenever I try to search for some value in the list by using the method "find_node". However, the output is always ""The value %d has not been found in the list." (this is in the method user_search.) I don't understand why. If the specific node is not found, it should return a NULL. However, if something was found, then it should return a pointer to the node inside the linked list and a message confirming the finding should be displayed.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|