![]() |
| ||
| Inserting in a sorted linked list(sorted alphabetically) [COLOR=Navy]Pls 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; } } *********************************************** |
| ||
| Re: Inserting in a sorted linked list(sorted alphabetically) Here is one method you could use to sort your linked list alphabetically: (I haven't tested this specific code but the idea is sound) First, push each node into an array of nodes: Node **array = new Node*[size]; Now sort your array of Nodes based on the first letter of each name: #include<algorithm>Now.. all you have to do is include a provision on what to do if the first 2 letters of a person's name are the same. Once you are done with all your sorting operations, turn the array of nodes back into a linked list. Make each node of the newly sorted list point to the next node in line by resetting all the *next pointers: head_ptr = Nodes[0]; That's it. You now have a head_ptr that points to beginning of a sorted linked list. |
| ||
| Re: Inserting in a sorted linked list(sorted alphabetically) This assumes that, if the list already exist, it is in 'name' order ... |
| All times are GMT -4. The time now is 9:21 am. |
Forum system based on vBulletin Copyright ©2000 - 2009, Jelsoft Enterprises Ltd.
©2003 - 2009 DaniWeb® LLC