Tuesday, March 17, 2015

Single Linked List : Operations

#include
#include

struct node {
    int data;
    struct node *link;
};


/* Function Prototypes */

void append (struct node **q, int data);
void display(struct node *q);
void addAtBegin(struct node **q, int data);
void addAtLocation(struct node **q, int pos, int data);
void count(struct node *q);
void delete(struct node **q, int data);


int main ()

{
    struct node *p = NULL;

    append(&p, 10);
    append(&p, 20);
    append(&p, 30);
    append(&p, 40);
    display(p);

    addAtBegin(&p, 3);
    addAtBegin(&p, 1);
    display(p);

    addAtLocation(&p, 4, 12);
    addAtLocation(&p, 6, 13);
    display(p);

    delete(&p, 40);
    display(p);
    //count(p);

}

void append (struct node **q, int data) /* Appends at the end of the list */
{
    struct node *temp;
    struct node *r;

    if (*q == NULL){ /* First node in the link */
        temp = (struct node *)(malloc(sizeof(struct node)));
        temp->data = data;
        temp->link = NULL;
        *q = temp;
    }else{
        r = *q;
        while(r->link != NULL){
            r = r->link;
        }
        temp = (struct node *)malloc (sizeof(struct node));
        temp->data = data;
        temp->link = NULL;
        r->link = temp;

    }
    return;
}
void display(struct node *q)
{
    if (q == NULL){
        printf("List is empty \n");
    }
    while(q != NULL){
        printf("%d\n", q->data);
        q = q->link;
    }
    printf("===============================\n");
}

void addAtBegin(struct node **q, int data)

{
    struct node *temp;

    if (*q == NULL){ /* This is the first node */
        temp = (struct node *)malloc(sizeof(struct node));
        temp->data = data;
        temp->link = NULL;
        *q = temp;
    }else{
        temp = (struct node *)malloc(sizeof(struct node));
        temp->data = data;
        temp->link = *q;
        *q = temp;
    }
    return;
}
void addAtLocation(struct node **q, int pos, int data)
{
    struct node *temp, *r;
    r = *q;
    int i;
    for (i = 1; i        r = r->link;
        if (r == NULL){
            printf("It is exceeded the no.of the links in the list\n");
            return;
        }
    }
        temp = (struct node *)malloc(sizeof(struct node));
        temp->data = data;
        temp->link = r->link;
        r->link = temp;

   
}
void count(struct node *q)
{
    int count=0;
    while (q != NULL){
        count++;
        q = q->link;
    }
    printf("Count = %d\n", count);
}

void delete(struct node **q, int data)
{
    struct node *temp, *old;
    temp = *q;

    while (temp != NULL){

        if(temp->data == data)
        {
            if (temp == *q){
                *q = temp->link;
            }else{
                old->link = temp->link;
            }
            free(temp);
            return;
        }
        else
        {
            old = temp;
            temp = temp->link;
        }
    }
    printf("Data is not found in the list\n");
}