linked list

L

Logan Lee

#include <iostream>
using namespace std;

struct node {
int data;
node* next;
};

int main() {
node* head;
node* newnode;
head=NULL;

for (int i=0; i<3; i++) {
newnode=new node;
newnode->data=i+1;
newnode->next=head;
head=newnode;
}

while (head!=NULL) {
cout << head->data << endl;
head=head->next;
}
cin.get();

}
 
P

Paul N

You haven't asked a question, but I'll make one comment:


#include <iostream>
using namespace std;

struct node {
       int data;
       node* next;

};

int main() {
    node* head;
    node* newnode;
    head=NULL;

    for (int i=0; i<3; i++) {

        newnode=new node;
        newnode->data=i+1;
        newnode->next=head;
        head=newnode;

Part of the idea behind C++ is that you have functions hidden in your
classes to do this sort of messy stuff, so that the users of the class
don't have to worry about it. The above four lines might then be
reduced to something like:

mylist.addnode(i+1);
 
J

Jorgen Grahn

You haven't asked a question, but I'll make one comment:




Part of the idea behind C++ is that you have functions hidden in your
classes to do this sort of messy stuff, so that the users of the class
don't have to worry about it. The above four lines might then be
reduced to something like:

mylist.addnode(i+1);

And then you address more and more weaknesses, until finally you end
up with std::list. It would be interesting to follow such a
transformation.

To the original poster: your code is basically C code. It's fine to
learn how to use the C part of C++ this way, but it's also important
to understand that you almost never write code like this in C++. You
use the standard containers -- sometimes std::list, but more often
std::vector and some others. You yourself can concentrate on more
interesting tasks.

/Jorgen
 
A

Andrey Tarasevich

#include <iostream>
using namespace std;

struct node {
int data;
node* next;
};

int main() {
node* head;
node* newnode;
head=NULL;

for (int i=0; i<3; i++) {
newnode=new node;
newnode->data=i+1;
newnode->next=head;
head=newnode;
}

while (head!=NULL) {
cout << head->data << endl;
head=head->next;
}
cin.get();
}

Memory leak.

Your 'head' pointer is the only access path that leads to your linked
list elements. And you wasted it in your output cycle.
 
A

Andrey Tarasevich

Memory leak.

Your 'head' pointer is the only access path that leads to your linked
list elements. And you wasted it in your output cycle.

.... although technically you still have 'newnode'. But the general point
still stands.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,537
Members
45,023
Latest member
websitedesig25

Latest Threads

Top