-
regarding linked list
iam storing the values in linked list in a sorted form
how can i do this i have to sorted out with item_num key
my code is
Code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct dllist {
int item_num;
char description[256];
int quantity;
float price;
struct dllist *next;
struct dllist *prev;
};
struct dllist *head, *tail;
void main()
{
struct dllist *record;
int item_no,quantity;
float price;
char description[256];
int i;
for(i=0;i<=4;i++)
{
printf("enter records \n");
record = (struct dllist *)malloc(sizeof(struct dllist));
scanf("%d",&item_no);
scanf("%s", &description);
scanf("%d", &quantity);
scanf("%f", &price);
record->item_num=item_no;
strcpy(record->description,description);
record->quantity=quantity;
record->price=price;
append_node(record);
}
for(record = head; record != NULL; record = record->next)
printf("%d \n",record->item_num);
}
void append_node(struct dllist *lnode) {
if(head == NULL) {
head = lnode;
lnode->prev = NULL;
} else {
tail->next = lnode;
lnode->prev = tail;
}
tail = lnode;
lnode->next = NULL;
}
thank u ,inadvance
sree
-
The simplest thing would be to use an "insertion sort" method inside your append_node() which should in this case be renamed to insert_node().
Insertion sort is based on finding the node that is greater (or lesser - depending on your sort order) and inserting the current item before the found node.
--
Mats
-
Haven't you learnt anything in your 77 posts to date?
- void main - wrong
- casting malloc - wrong
- non-existent indentation
- incorrect use of pointers in scanf with %s
To answer your other question, you need an insert() function, which walks down the list comparing each item_num with the one you want to add. When you get to the point where the 'prev' node is less and the 'next' node is greater-equal, that is where you insert the new node. Plus detecting the various edge conditions such as insert into an empty list, insert at head of list etc.