|
-
October 9th, 2004, 07:02 PM
#9
Re: Method not searching properly...
Code:
#include <stdio.h>
#include <stdlib.h>
struct node
{
int data;
struct node *next;
};
void insert_node(struct node ** , int );
void remove_node(struct node ** );
void view_nodes(struct node ** );
void remove_nodes(struct node ** );
void custom_insert(struct node ** );
int main()
{
struct node *list = (struct node * )malloc(sizeof(struct node));
list -> next = NULL;
list -> data = -999;
int i = 0;
for(i = 0; i < 100; i++)
{
insert_node(&list, i + 1);
}
printf("View nodes...\n");
view_nodes(&list);
printf("\n\n");
custom_insert(&list);
printf("View nodes...\n");
view_nodes(&list);
printf("\n\nDeleted nodes...\n");
remove_nodes(&list);
free(list);
printf("\n\n");
return 0;
}
void insert_node(struct node ** head, int value)
{
struct node * new_node = (struct node *)malloc(sizeof(struct node));
new_node -> data = value;
new_node -> next = (*head);
(*head) = new_node;
}
void remove_node(struct node ** head)
{
struct node * temp = *head;
struct node * next_node = NULL;
if(temp != NULL)
{
next_node = temp -> next;
printf("%3d, ", temp -> data);
free(temp);
(*head) = next_node;
}
}
void view_nodes(struct node ** head)
{
struct node * temp = *head;
while(temp != NULL)
{
if(temp -> data != -999)
{
printf("%3d, ", temp -> data);
}
temp = temp -> next;
}
}
void remove_nodes(struct node ** head)
{
struct node * to_be_del = NULL;
while(temp_first -> next != NULL)
{
to_be_del = temp_first;
temp_first = temp_first -> next;
printf("%3d|", to_be_del -> data);
free(to_be_del);
}
}
void custom_insert(struct node ** head)
{
int position = 0;
int value = 0;
int iterations = 0;
struct node * new_node;
struct node * node_in_list = (* head);
printf("In which position would you like to insert the node - > ");
scanf("%d", &position);
printf("Which value would you like to insert - > ");
scanf("%d", &value);
while(node_in_list -> next != NULL)
{
if(iterations == position)
{
new_node = (struct node * )malloc(sizeof(struct node));
new_node -> next = NULL;
new_node -> data = value;
new_node -> next = node_in_list -> next;
node_in_list -> next = new_node;
}
iterations++;
node_in_list = node_in_list -> next;
}
}
The last method isn't working too well. I'm trying to insert a node in a specific part of the list. I think I messed the pointers up. What I'm trying to do is have the program print out some integers to the command console and then the user has select a position in the list and that's where the new value will be inserted (position 1 will be at the very front, position 3 will be [(value1)(value2)(new_inserted_value)(value 3)....(value n)].) Thanks in advance.
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
|