Sunday 8 September 2013

Sunday 8 September 2013

Singly LinkedList insertion



Simple LinkedList Program(LIFO)

Singly linked list is the most basic linked data structure. In this the elements can be placed anywhere in the heap memory unlike array which uses contiguous locations. Nodes in a linked list are linked together using a next field, which stores the address of the next node in the next field of the previous node i.e. each node of the list refers to its successor and the last node contains the NULL reference. It has a dynamic size, which can be determined only at run time.



 Single Linked List A self referential data structure. A list of elements, with a head and a tail; each element points to another of its own kind. Double Linked List A self referential data structure. A list of elements, with a head and a tail; each element points to another of its own kind in front of it, as well as another of its own kind, which happens to be behind it in the sequence.  Circular Linked List Linked list with no head and tail - elements point to each other in a circular fashion.

Basic operations of a singly-linked list are:

Insert – Inserts a new element at the end of the list.
Delete – Deletes any node from the list.
Find – Finds any node in the list.
Print – Prints the list.



#include <stdio.h>
#include <stdlib.h>

struct node{
    struct node *link;
    int data;
    };
  
    void insert(struct node **,int);
    void display(struct node *);
    int count(struct node *);
  
    int main(){
        struct node *s;
        s=NULL;
        insert(&s,10);
        insert(&s,20);
        insert(&s,40);
        insert(&s,50);

        display(s);
        count(s);
        return 0;
    }
  
    void insert(struct node **s,int num){
        struct node *temp;
        temp=(struct node*)malloc(sizeof(struct node));
        temp->data=num;
        temp->link=*s;
        *s=temp;
    }
    void display(struct node *s){
  
        while(s!=NULL){
            printf("%d \n",s->data);
            s=s->link;
        }
        printf("\n");
    }

int count(struct node *s){
        int i;
        i=0;
        while(s!=NULL){
            
            s=s->link;
            i++;
        }
        printf("%d",i);
    }


output:
Executing the program....
$demo
50 
40 
20 
10 

4


No comments:

Post a Comment