Please I need help on how to insert elements into a sorted linked list.I actually have a list that contains names and scores for students and I want the elements to be inserted into the right postion such that the names of individual students are arranged alphabetically.
This is my code but something seems to be wrong.
#include "iostream"
using namespace std;
struct Node
{
char *name;
int score;
Node *next;
};
Node *head=NULL;
void InsertItem(Node * &head);
void main()
{
InsertItem(head);
}
void InsertItem(Node * &head)
{
Node *temp, *previous,*current; /*previous stores the node before the insertion point*/
temp=new Node();
cout<<"Enter name";
cin>>temp->name;
cout<<"Enter score";
cin>>temp->score;
if (head == NULL) /* first node in the list */
{
head = temp;
}
else if (strcmp(head->name,temp->name)>=0)/* insert at the head */
{
temp->next = head;
head = temp;
}
else
{
previous = head; /* trailing pointer */
current = head->next;
while ((current != NULL) && strcmp(current->name,temp->name)<0)
{
previous = current;
current = current->next;
}
temp->next=previous->next;
previous->next=temp;
}
}