linked list problem
I will write a simple logic to insert a node at beginning of linked list.
first define a structure (define globally)to create a node, as you know that node contains two parts one is data part and another one is link part (to store next node address).
struct node{
int data;
struct node* next;
}
define a head node globally to store first node address in linked list.
struct node* head;
In main function intialize head node to NULL.
Now create a node(called temp) to add element at beginning
struct node* temp;//for link
//Allocate memory using malloc
temp = (node*)malloc(sizeof(struct node));
temp->data = element;//your value here
temp->next=head;
head=temp;// assigning temp node address in head node
temp->next=head;
Above instruction works for when element is not present in the list and also when any number of elements are present in the list.Because in main function we intialized head to NULL;
I'm guessing you're a student or something. The problem is very basic and should jump out at if immediately if you understand linked lists.
- Sarah August 24, 2014Here's a hint, something is being modified early.