Monday, September 19, 2011

#C_CODE: Single Linked List


#include <stdio.h>
#include <malloc.h>


typedef struct singlelink node;
struct singlelink
{
    int data;
    node *next;
};

void append(node **q, int num)
{
    node *temp = *q, *r = NULL;
  
    r = (node *)malloc(sizeof(node));
    r->data = num;
    r->next = NULL;
    if(NULL == temp)
    {
        *q = r;
    }    
    else
    {
        while(NULL != temp->next)
            temp = temp->next;
        temp->next = r;
    }
}

void display(node *temp)
{
    printf("\nThe list: ");
    while(temp)
    {
        printf("%d ",temp->data);
        temp = temp->next;
    }

}

void reverse(node **q)
{
    node *temp1 = *q, *temp2 = NULL, *temp3 = NULL;
  
    while(temp1)
    {
       temp2 = temp1->next; // Save the next pointer
       temp1->next = temp3; // Update the next
       temp3 = temp1; // Update the previous
       temp1 = temp2;
    }

    if(temp3)
        *q = temp3;
}


void delete(node **q, int val)
{
    node *temp = *q, *old = NULL;

    while(temp)
    {
        if(temp->data == val)
        {
           if(temp == *q)
              *q = temp->next;       
           else
                old->next = temp->next;
            free(temp);
        }
        else
        {
            old = temp;
            temp = temp->next;
        }
    }
}

int main()
{
    node *head = NULL;
    unsigned int i;

    for(i=0; i<10; i++)
        append(&head,i);
    display(head);
 
    reverse(&head);
    display(head);

    delete(&head,5);
    display(head);

    return 0;
}

No comments: