473,811 Members | 3,811 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Linked list program question..

SKP
Hi,
I am trying do a basic liked list program, where i am adding nodes at
the end. Adding part is fine, but removing part is not working.
Here is the code:
---------

#include<string >
class List {

struct node {
string *s;
node *next;
} *head;
public:
List() { head = 0;};
~List() {delete head;}
void Add(string *str);
string *Remove();
void print();
};
void List::Add(strin g *str)
{
cout<< *str <<endl;
if(head) {
struct node* cnode = head;
while(cnode->next) cnode=cnode->next;
struct node *temp = new struct node;
temp->s = str;
temp->next = NULL;
cnode->next = temp;
}
else {
head = new struct node;
head->s = str;
head->next = NULL;
}
}
string *List::Remove()
{
struct node *cnode = head;
while(cnode->next) {
cnode = cnode->next;
}
string *p = cnode->s;
cnode = NULL;
delete cnode;
return p;
}
void List::print()
{
struct node *cnode = head;
while(cnode) {
cout<< *(cnode->s)<<endl;
cnode = cnode->next;
}
}
int main()
{
string StrObjs[] = {"str1","str2", "str3","str 4"};
List L;
const int total =sizeof(StrObjs )/sizeof(*StrObjs );
for(int i = 0;i < total;i++)
L.Add(&StrObjs[i]);
L.print();
string *temp = L.Remove();
cout<<"popped element = "<<*temp<<e ndl;
temp = L.Remove();
cout<<"popped element = "<<*temp<<e ndl;
temp = L.Remove();
cout<<"popped element = "<<*temp<<e ndl;
cout<<"popped element = "<<*temp<<e ndl;
temp = L.Remove();
L.print();
return 0;
}
---------

The output it gives is:

--
str1
str2
str3
str4
str1
str2
str3
str4
popped element = str4
popped element = str4
popped element = str4
popped element = str4
str1
str2
str3
str4
--------

which is not the expected one. Please help in correcting it and any
suggestions on improving this program are appreciated.

Thanks in adv,

SKP.

Mar 2 '06 #1
1 2609
SKP wrote:
Hi,
I am trying do a basic liked list program, where i am adding nodes at
the end. Adding part is fine, but removing part is not working.
Here is the code:
---------
I'll add some style comments, too.
#include<string >
class List {

struct node {
string *s;
Why do you use pointers to strings?
Also, it should be std::string.
node *next;
} *head;
public:
List() { head = 0;};
List() : head(0) {}
~List() {delete head;}
void Add(string *str);
Again, I wouldn't use a pointer here. The string should also be const. A
reference would be best, so it would be:

void Add(const std::string& str);
string *Remove();
void print();
This function doesn't modify your object. Such functions should be made
const, like:

void print() const;
};
void List::Add(strin g *str)
{
cout<< *str <<endl;
if(head) {
struct node* cnode = head;
You can leave out the struct keyword here (and in all the following uses of
your node struct). It's superfluous.
while(cnode->next) cnode=cnode->next;
struct node *temp = new struct node;
temp->s = str;
temp->next = NULL;
cnode->next = temp;
}
else {
head = new struct node;
head->s = str;
head->next = NULL;
}
}
string *List::Remove()
{
struct node *cnode = head;
while(cnode->next) {
cnode = cnode->next;
}
string *p = cnode->s;
cnode = NULL;
delete cnode;
Well, here's your problem. First, you overwrite your cnode pointer with a
null pointer, then _afterwards_, you try to delete it. So in fact, you
delete a null pointer, which does nothing. The object that cnode was
pointing to before is still existing.
What you need to do is remember the pointer to the previous node, because
that one's next pointer needs to be deleted and then set to null. And that
means you can't just exchange the cnode = NULL and the delete line, because
cnode is not the last node's next pointer, but a copy of it. I don't give
you a solution to save you the learning experience.
return p;
}
void List::print()
{
struct node *cnode = head;
while(cnode) {
cout<< *(cnode->s)<<endl;
cnode = cnode->next;
}
}
int main()
{
string StrObjs[] = {"str1","str2", "str3","str 4"};
List L;
const int total =sizeof(StrObjs )/sizeof(*StrObjs );
for(int i = 0;i < total;i++)
L.Add(&StrObjs[i]);
L.print();
string *temp = L.Remove();
cout<<"popped element = "<<*temp<<e ndl;
temp = L.Remove();
cout<<"popped element = "<<*temp<<e ndl;
temp = L.Remove();
cout<<"popped element = "<<*temp<<e ndl;
cout<<"popped element = "<<*temp<<e ndl;
temp = L.Remove();
L.print();
return 0;
}
---------


Mar 2 '06 #2

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

Similar topics

7
4834
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...
7
2616
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...
57
4310
by: Xarky | last post by:
Hi, I am writing a linked list in the following way. struct list { struct list *next; char *mybuff; };
7
1419
by: alternativa | last post by:
Hello, I'm a beginner in C programming and I have a problem that probably will seem trivial to most of you, however I can't find a solution... So, I have to write a data base - program should ask the user about the data and then do some operations like sorting etc. I decided to use a linked list. The code looks as follows: #include<stdio.h> #include<string.h> #include<stdlib.h>
3
472
by: Little | last post by:
Could someone tell me what I am doing wrong here about declaring mutiple double linked lists. This is what the information is for the project and the code wil be below that. Thank your soo much for your assitance in helping me solve this problem. Information: Create 4 double linked lists as follows: (a) A double linked list called NAMES which will contain all C like
4
4288
by: FBM | last post by:
Hi, I am working on a program that simulates one of the elements of ATM. The simulation stores events which occurs every some milliseconds for a certain amount of time. Every time that an event is stored in a double linked list, the whole list is sorted for the next round. My problem appears when subjecting the program to heavy load, that is, when I run the simulation for more than 10,000 miliseconds (every event occurs in...
6
16136
by: Julia | last post by:
I am trying to sort a linked list using insertion sort. I have seen a lot of ways to get around this problem but no time-efficient and space-efficient solution. This is what I have so far: struct node { int x; struct node *next; };
6
5337
by: Fazana | last post by:
I was doing one of the question but my program was not working properly. Can anyone help me with it pliz........ Here is the question for the program Question. Part 1. Add the function splitAt to split a linked list at a node whose Data is given. Suppose you have a list with the elements
9
2846
by: william | last post by:
When implementing Linked list, stack, or trees, we always use pointers to 'link' the nodes. And every node is always defined as: struct node { type data; //data this node contains ... node * nPtr; //the next node's pointer }
6
4162
by: tgnelson85 | last post by:
Hello, C question here (running on Linux, though there should be no platform specific code). After reading through a few examples, and following one in a book, for linked lists i thought i would try my own small program. The problem is, I seem to be having trouble with memory, i.e. sometimes my program will work and display the correct output, and sometimes it will not and display garbage (in a printf call) so i assume i have been using...
0
9724
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
9604
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
10379
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...
0
9201
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
7665
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
5552
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...
0
5690
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4336
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
3015
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.