0

I am looking to get some help understanding on how I would implement a sorted linked list at the point of insertion? Below is an addItem function with the option to add at the beginning of the list or at the end. Is it possible to insert (thereby sorting) depending on the value given in var.number; for example?

struct structName {
    int number;
    int number2;
    char aString;
    struct structName *next;
};

struct structName *head = NULL;
struct structName *curr = NULL;
struct structName *element = NULL;

struct Struct var;

struct structName* addItem(struct structName var, bool appendList) {

    struct structName *pointer = (struct structName*)malloc(sizeof(struct structName));

    pointer->someString = var.aString;
    pointer->aNumber = var.number2;
    pointer->anotherNumber = var.number;
    pointer->next = NULL;

    if(appendList) {
        curr->next = pointer;
        curr = pointer;
    }
    else {
        pointer->next = head;
        head = pointer;
    }  

    return pointer;
}
archienorman
  • 1,434
  • 3
  • 20
  • 36
  • There are **countless** questions concerning linked lists. I'm sure you'll find your answer on Google or by searching StackOverflow. – cadaniluk Nov 08 '15 at 15:52
  • 3
    Possible duplicate of [How do you insert into a sorted linked list?](http://stackoverflow.com/questions/1320460/how-do-you-insert-into-a-sorted-linked-list) – Kaz Nov 08 '15 at 15:52

1 Answers1

0

it's simple. if you want to insert into a sorted list. Then before inserting the list you have to traverse through the list, until you go to the end of list or find a node value which is greater than the current list value. Then Insert your list.

Sigcont
  • 717
  • 2
  • 8
  • 16
  • ...in this way the list remains sorted but you may not accept commands like "insert at head" or" insert at end" because then the list becomes unsorted. – Paul Ogilvie Nov 08 '15 at 16:54