Sunday, April 8, 2012

link list for accepting n number


program to create link list for accepting n number of lines from user and creating one node each for one line. only one global variable root is used,so while refering to list after creation, we will be refering from the last node towards the first node. dispayed in reverse order.

INCLUDE files:

//**************************************
//INCLUDE files for :Linked List for storing strings
//**************************************
# include <stdio.h>
# include <conio.h>
# include <alloc.h>
# include <string.h>
# include <stdlib.h>
//**************************************
// Name: Linked List for storing strings
// Description:program to create link list for accepting n number of lines from user
and creating one node each for one line.
only one global variable root is used,so while refering to list
after creation, we will be refering from the last node towards the
first node.
dispayed in reverse order.
// By: Yogesh Ranade
//
//
// Inputs:any number of strings
//
// Returns:all the strings
//
//Assumes:None
//
//Side Effects:no
//This code is copyrighted and has limited warranties.
//Please see http://www.Planet-Source-Code.com/xq/ASP/txtCodeId.6112/lngWId.3/qx/vb/scripts/ShowCode.htm
//for details.
//**************************************
 
/////////////////////////////////////////////////////////
typedef struct node
 
 
    {
    char *info;
    struct node *next;
}NODE,*NODEPTR;
/////////////////////////////////////////////////////////
NODEPTR root=NULL;
/////////////////////////////////////////////////////////
NODEPTR allocnode(void);
char * strsave(char *s);
void createlist(char *s);
void displist(NODEPTR np);
void freelist(void);
/////////////////////////////////////////////////////////
void main(void)
 
 
    {
    char s[100];
    clrscr();
    while(1)
 
 
        {
        gets(s);
        if((strcmp(s,"quit")==0) ||(strcmp(s,"QUIT")==0))
                break;
        createlist(s);
    }
    displist(root);
    freelist();
    getch();
}
NODEPTR allocnode(void)
 
 
    {
    NODEPTR p;
    p=(NODEPTR)malloc(sizeof(NODE));
    if(p==NULL)
 
 
        {
        printf("Memory limit");
        exit(1);
    }
    return(p);
}
char * strsave(char *s)
 
 
    {
    char *p;
    p=(char *)malloc(strlen(s)+1);
    if(p==NULL)
 
 
        {
        printf("Memory limit");
        exit(1);
    }
    strcpy(p,s);
    return(p);
}
void createlist(char *s)
 
 
    {
    NODEPTR np;
    np=allocnode();
    np->info=strsave(s);
    np->next=root;
    root=np;
}
void displist(NODEPTR np)
 
 
    {
    while(np!=NULL)
 
 
        {
        printf("\n%s",np->info);
        np=np->next;
    }
}
void freelist(void)
 
 
    {
    NODEPTR np=root,np1;
    while(np!=NULL)
 
 
        {
        free(np->info);
        np1=np->next;
        free(np);
        np=np1;
    }
    root=NULL;
}

No comments:

Post a Comment