Insertion in Linked list

0 kartik watwani · February 10, 2015
The Below given code is giving very strange result.why is it so and how to rectify it?




#include<iostream>
using namespace std;
int main()
{
struct kt
{
    int info;
    kt * next;
}*start,*newptr,*save,*show;
start=NULL;
newptr=NULL;
save=NULL;
    int item;
    char ch='y';
    while(ch=='y'||ch=='Y')
    {
        cout<<"Enter element info: ";
        cin>>item;
        cout<<"New element is being created";
        newptr=new kt;
        if(newptr==NULL)
        {
            cout<<"Element not created";

        }
        else{

            cout<<"Element is created !!"<<endl;
        }
        cout<<"Inserting element into list"<<endl;
        if(start==NULL)
        {
            start=newptr;
        }
        else{
            save=start;
            start=newptr;
            newptr->next=save;

        }
         show=start;
        cout<<"Now the list is as follows"<<endl;
        while(show!=NULL)
        {
            cout<<show->info<<endl;;
            show=show->next;
        }
    }



}


Post a Reply

Replies

Oldest  Newest  Rating
0 Mathias Frits Rørvik · February 10, 2015
1. Your code is almost unreadable
2. You are allocating memory you are never deleting.
3. Clean up your code, and tell us what you are actually trying to achieve.
  • 1

C++

106,986 followers
About

Used in many types of software including music players, video games, and many large scale applications.

Links
Moderators
Bucky Roberts Administrator