Senthil wrote :
> Write a Linked List Program in C and C++.
> Single Linked List only.
> 
/* Linked List program. A very simple one to understand the basics */
#include<stdio.h>
#include<stdlib.h>
struct node {
        int data;
        struct node* next;
};
int main(int argc,char **argv)
{
        struct node* head=NULL;
        struct node* second=NULL;
        struct node* third=NULL;
        head=malloc(sizeof(struct node));
        second=malloc(sizeof(struct node));
        third=malloc(sizeof(struct node));
        head->data=1;
        head->next=second;
        second->data=2;
        second->next=third;
        third->data=3;
        third->next=NULL;
return 0;
}
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
/* Linked List Program in C Plus Plus */
#include<iostream>
using namespace std;
class list
{
        private:
                struct node {
                        int data;
                        struct node *next;
                };
                struct node *head,*first,*second;
        public:
                list();
                ~list();
                void addnode();
};
list::list()
{
        head=NULL;
        first=NULL;
        second=NULL;
}
list::~list()
{
        while(head != NULL)
        {
                node *temp;
                temp=head;
                head=head->next;
                delete temp;
        }
}
void list::addnode()
{
        head=(node *)malloc(sizeof(struct node));
        first=(node *)malloc(sizeof(struct node));
        second=(node *)malloc(sizeof(struct node));
        head->data=1;
        head->next=first;
        first->data=2;
        first->next=second;
        second->data=3;
        second->next=NULL;
}
int main(int argc,char **argv)
{
        list listobj;
        listobj.addnode();
}
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Observations:
- Struct node * head,first,second; does not serve the purpose. Either
they should as in the first program or as in the second program
- Allocation of memory, the first program accepted without typecasting
to (node *) whereas the second cpp program did not.
-- 
O.R.Senthil Kumaran
http://uthcode.sarovar.org
 
No comments:
Post a Comment