Question regarding cases of linked lists

Oct 2, 2010 at 6:58am
Guys, this might be kind of a silly questions but I would like a concrete answer on this so I will ask anyways.

Are there 4 cases in inserting and removing a node?
1.) inserting the first node if the list is empty
2.) inserting a node at the beginning of the list
3.) inserting a node in the middle of the list
4.) inserting a node at the end of the list

(same concept for removing)

I ask because my remove and insert functions look almost identical (with the exception of deleting the node) and if there are less cases then I can shorten up my code.

Thanks in advance.
Oct 2, 2010 at 7:08am
While logically these are separate cases, depending on your implementation, one could be sufficient.
Oct 2, 2010 at 7:24am
Well in the case that you're reading numbers or words from a file and putting them in numerical/alphabetical order then these would be the four separate cases, right?
Oct 2, 2010 at 9:13am
That's not what I meant by 'implementation'
example - a single linked list:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
struct node{
    //some data..
    node* next;
};

struct list{
    node* head;

    void add(node*& where, /*data*/){
        node* tmp = where;
        node* n = new node;
        //assign data to n->data
        n->next = tmp;
        where = n;
    }
};

This should work (haven't tested it) in all four cases. I'm not sure if a double linked list would work as nicely. You may have to add few ifs.
Topic archived. No new replies allowed.