473,786 Members | 2,712 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Linked List Help

hi! i am beginner c++ programmer. Here is my code. I can delete any
entered record but if i want to delete first and last node of the list
it goes into indefinite loop, although the compilation is successfull.
Can anybody suggest any clue what and where it went wrong?
#include <stdio.h>
#include <alloc.h>
#include <ctype.h>
#include <conio.h>
#include <iostream.h>

struct student
{
int st_id;
char name[50];
student *ptr;
};
student *fptr, *cptr, *nptr;

void create(void);
void display (void);
void del(void);
void main(void)
{
clrscr();
create();
display();
del();
display();
} //end of main

void create (void)
{
char ch;
do{
nptr=(student*) malloc(sizeof(s truct student));
cout<<"\n\tEnte r Student ID = ";cin>>nptr->st_id;
cout<<"\n\tEnte r Student Name = ";gets(nptr->name);
if (fptr==NULL)
{fptr = cptr = nptr;}
else
{cptr->ptr=nptr;
cptr = nptr;}
nptr = NULL;

cout<<"\n\tEnte r another record (y/n)";
ch=tolower(getc he());
}while (ch!='n');
cptr->ptr=NULL;

} //end of create
void display(void)
{
char ch;
cptr=fptr;
do{
cout<<"\n\tStud ent ID = ";cptr->st_id;
cout<<"\n\tStud ent Name = ";puts(cptr->name);
cout<<"\n\tView another record (y/n";
ch=tolower(getc he());
if (ch=='y');
cptr=cptr->ptr;
}while (ch!='n' && cptr !=NULL);

} //end of display
void del(void)
{
student *pptr;
pptr=cptr=fptr;
int id;
cout<<"\n\tEnte r record to delete = ";cin>>id;
do{
if (cptr->st_id == id)
{
cout<<"\n\tStud ent ID = " <<cptr->st_id;
cout<<"\n\tStui dent Name = "<<puts(cpt r->name);
cout<<"\n\tThe above record will be deleted";
cout<<endl;
pptr->ptr=cptr->ptr;
}
pptr=cptr;
cptr=cptr->ptr;
}while(cptr->ptr!=NULL);

} //end of delete

Aug 18 '05 #1
3 1623

"imranzafar " <im************ @gmail.com> wrote in message
news:11******** **************@ g44g2000cwa.goo glegroups.com.. .
hi! i am beginner c++ programmer. Here is my code. I can delete any
entered record but if i want to delete first and last node of the list
it goes into indefinite loop, although the compilation is successfull.
Can anybody suggest any clue what and where it went wrong?
#include <stdio.h>
#include <alloc.h>
#include <ctype.h>
#include <conio.h>
#include <iostream.h>

struct student
{
int st_id;
char name[50];
student *ptr;
};
student *fptr, *cptr, *nptr;

void create(void);
void display (void);
void del(void);
void main(void)
{
clrscr();
create();
display();
del();
display();
} //end of main

void create (void)
{
char ch;
do{
nptr=(student*) malloc(sizeof(s truct student));
cout<<"\n\tEnte r Student ID = ";cin>>nptr->st_id;
cout<<"\n\tEnte r Student Name = ";gets(nptr->name);
if (fptr==NULL)
{fptr = cptr = nptr;}
else
{cptr->ptr=nptr;
cptr = nptr;}
nptr = NULL;

cout<<"\n\tEnte r another record (y/n)";
ch=tolower(getc he());
}while (ch!='n');
cptr->ptr=NULL;

} //end of create
void display(void)
{
char ch;
cptr=fptr;
do{
cout<<"\n\tStud ent ID = ";cptr->st_id;
cout<<"\n\tStud ent Name = ";puts(cptr->name);
cout<<"\n\tView another record (y/n";
ch=tolower(getc he());
if (ch=='y');
cptr=cptr->ptr;
}while (ch!='n' && cptr !=NULL);

} //end of display
void del(void)
{
student *pptr;
pptr=cptr=fptr;
int id;
cout<<"\n\tEnte r record to delete = ";cin>>id;
do{
if (cptr->st_id == id)
{
cout<<"\n\tStud ent ID = " <<cptr->st_id;
cout<<"\n\tStui dent Name = "<<puts(cpt r->name);
cout<<"\n\tThe above record will be deleted";
cout<<endl;
pptr->ptr=cptr->ptr;
}
pptr=cptr;
cptr=cptr->ptr;
}while(cptr->ptr!=NULL);

} //end of delete


Hmmm, you need to better structure your code perhaps. For example, you are
bundling list manipulation with user level IO, allocating memory with
malloc() without free()ing any, etc. Basically, the first/last node in a
linked list must be treated carefully, usually with if-then-else branchings.

How to solve the problem? Get yourself a debugger and step through the code.
This took me seconds to find the error, so I think it wouldn't take you long
either.

Ben
Aug 18 '05 #2
imranzafar wrote:
hi! i am beginner c++ programmer. Here is my code. I can delete any
entered record but if i want to delete first and last node of the list
it goes into indefinite loop, although the compilation is successfull.
Can anybody suggest any clue what and where it went wrong?
It went wrong in not using high-level features of C++. You are a beginner
c++ programmer. So maybe, you want to avoid getting into the dark corners
of pointer fiddling where it is not needed.

If it is up to you, I would suggest learning about the standard library
first, then classes, exceptions, templates, and *finally* pointers and
arrays.

#include <stdio.h>
#include <alloc.h>
#include <ctype.h>
#include <conio.h>
#include <iostream.h>
Here are the headers that I would use:

#include <string>
#include <iostream>
#include <algorithm>
#include <list>
#include <sstream>

struct student
{
int st_id;
char name[50];
student *ptr;
};
a) char name [50] is not good.
b) Why do you insist on rolling your own list code?
So:

struct student {
int st_id;
std::string name;
};

And since any nice type should come with I/O, we add:

std::istream & operator>> ( std::istream & i_str, student & s ) {
if ( ! ( ( i_str >> s.st_id ) && ( i_str >> s.name ) ) ) {
// throw something
}
return( i_str );
}

std::ostream & operator<< ( std::ostream & o_str, student const & s ) {
o_str << s.st_id << ' ' << s.name << ' ';
return( o_str );
}

student *fptr, *cptr, *nptr;

void create(void);
void display (void);
void del(void);
void main(void)
{
clrscr();
create();
display();
del();
display();
} //end of main
void create (void)
{
char ch;
do{
nptr=(student*) malloc(sizeof(s truct student));
cout<<"\n\tEnte r Student ID = ";cin>>nptr->st_id;
cout<<"\n\tEnte r Student Name = ";gets(nptr->name);
if (fptr==NULL)
{fptr = cptr = nptr;}
else
{cptr->ptr=nptr;
cptr = nptr;}
nptr = NULL;

cout<<"\n\tEnte r another record (y/n)";
ch=tolower(getc he());
}while (ch!='n');
cptr->ptr=NULL;

} //end of create

Let us take the issues apart:

struct bad_input {}; // flags invalid input
struct end_input {}; // the user wants to stop

student prompt_for_stud ent ( void ) {
student result;
std::string input;
std::cout << "Please enter student id: ";
if ( ! std::getline( std::cin, input ) ) {
throw ( bad_input() );
}
if ( input == "" ) {
throw( end_input() );
}
std::stringstre am s_str ( input );
if ( ! ( s_str >> result.st_id ) ) {
throw ( bad_input() );
}
std::cout << "Please enter student name: ";
if ( ! std::getline( std::cin, result.name ) ) {
throw( bad_input() );
}
return( result );
}
student_list read_students ( void ) {
student_list result;
try {
while( true ) {
result.push_bac k( prompt_for_stud ent() );
}
}
catch( end_input ) {}
catch( bad_input ) {
std::cout << "Can't you even enter something that simple? Go home!\n";
throw;
}
return( result );
}

void display(void)
{
char ch;
cptr=fptr;
do{
cout<<"\n\tStud ent ID = ";cptr->st_id;
cout<<"\n\tStud ent Name = ";puts(cptr->name);
cout<<"\n\tView another record (y/n";
ch=tolower(getc he());
if (ch=='y');
cptr=cptr->ptr;
}while (ch!='n' && cptr !=NULL);

} //end of display

void print_student ( student const & s ) {
std::cout << s << '\n';
}

void del(void)
{
student *pptr;
pptr=cptr=fptr;
int id;
cout<<"\n\tEnte r record to delete = ";cin>>id;
do{
if (cptr->st_id == id)
{
cout<<"\n\tStud ent ID = " <<cptr->st_id;
cout<<"\n\tStui dent Name = "<<puts(cpt r->name);
cout<<"\n\tThe above record will be deleted";
cout<<endl;
pptr->ptr=cptr->ptr;
}
pptr=cptr;
cptr=cptr->ptr;
}while(cptr->ptr!=NULL);

} //end of delete


You do not need your own code here. A list is deleted by calling the
clear()-method:
int main ( void ) {
student_list l = read_students() ;
std::for_each( l.begin(), l.end(), print_student );
std::cout << "\nDeleting list.\n";
l.clear();
std::for_each( l.begin(), l.end(), print_student );
}

Best

Kai-Uwe Bux
Aug 18 '05 #3
Its really nice of you two guys. I really apprciate your help and
Kai-Uwe Bux special thanks to you for taking out your time and
rewriting the whole code again. I really really appreicate you.

Aug 19 '05 #4

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

7
4832
by: Chris Ritchey | last post by:
Hmmm I might scare people away from this one just by the title, or draw people in with a chalange :) I'm writting this program in c++, however I'm using char* instead of the string class, I am ordered by my instructor and she does have her reasons so I have to use char*. So there is alot of c in the code as well Anyways, I have a linked list of linked lists of a class we defined, I need to make all this into a char*, I know that I...
5
859
by: Dream Catcher | last post by:
1. I don't know once the node is located, how to return that node. Should I return pointer to that node or should I return the struct of that node. 2. Also how to do the fn call in main for that LOCATE subroutine that returns a node???? Any help would be appreciated. Thanks
5
6063
by: John N. | last post by:
Hi All, Here I have a linked list each containing a char and is double linked. Then I have a pointer to an item in that list which is the current insertion point. In this funtion, the user hits the right and left keys to move this insertion point (cursor) Here is the problem:
7
2614
by: Kieran Simkin | last post by:
Hi all, I'm having some trouble with a linked list function and was wondering if anyone could shed any light on it. Basically I have a singly-linked list which stores pid numbers of a process's children - when a child is fork()ed its pid is added to the linked list. I then have a SIGCHLD handler which is supposed to remove the pid from the list when a child exits. The problem I'm having is that very very occasionally and seemingly...
1
3318
by: Little | last post by:
Hello everyone. I am trying to do the following program and am unable to get the beginning portion to work correctly. The scanner works when I print the statements without the double linked list portion but I just need help with the beginning portion with the double linked lists. Here is the information needed to understand the code: Create 4 double linked lists as follows: (a) A double linked list called NAMES which will contain all...
12
3954
by: joshd | last post by:
Hello, Im sorry if this question has been asked before, but I did search before posting and couldnt find an answer to my problem. I have two classes each with corresponding linked lists, list1 and list2, each node within list1 has various data and needs to have a pointer to the corresponding node in list2, but I cant figure out how to do this. Could someone explain what I might be missing, or maybe point me in the direction of a good...
1
15553
by: theeverdead | last post by:
Ok I have a file in it is a record of a persons first and last name. Format is like: Trevor Johnson Kevin Smith Allan Harris I need to read that file into program and then turn it into a linked list. So on the list I can go Trevor, Kevin, Allan in a straight row but I can also call out there last name when I am on their first name in the list. Sorry if it doesn't make sense trying to explain best I can. So far I have // list.cpp
0
8633
by: Atos | last post by:
SINGLE-LINKED LIST Let's start with the simplest kind of linked list : the single-linked list which only has one link per node. That node except from the data it contains, which might be anything from a short integer value to a complex struct type, also has a pointer to the next node in the single-linked list. That pointer will be NULL if the end of the single-linked list is encountered. The single-linked list travels only one...
2
1700
by: phiefer3 | last post by:
Ok, first of all I'm not sure if this is the correct forum for this question or not. But hopefully someone can help me or at least point me in the direction of the forum this belongs. First of all, I am using C++, however it's managed C++ or visual C++, or whatever microsoft calls it. I'm using MSVS2005, and working on a Windows Forms Application project from the C++ projects tab. I'm pointing this out because apparently the syntax used in...
7
5773
by: QiongZ | last post by:
Hi, I just recently started studying C++ and basically copied an example in the textbook into VS2008, but it doesn't compile. I tried to modify the code by eliminating all the templates then it compiled no problem. But I can't find the what the problem is with templates? Please help. The main is in test-linked-list.cpp. There are two template classes. One is List1, the other one is ListNode. The codes are below: // test-linked-list.cpp :...
0
9655
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9497
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10169
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10110
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8993
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7517
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6749
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5398
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
3
2894
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.