Welcome to Dream.In.Code
Become a C++ Expert!

Join 137,210 C++ Programmers for FREE! Get instant access to thousands of C++ experts, tutorials, code snippets, and more! There are 2,280 people online right now. Registration is fast and FREE... Join Now!




linked lists

 
Reply to this topicStart new topic

linked lists

emeighty
8 Jul, 2008 - 08:01 PM
Post #1

New D.I.C Head
*

Joined: 1 Jul, 2008
Posts: 9

Thank you all for posting great help on my last question. This is one hell of a site for knowledge.

I have another question. I am starting on pointers and linked lists. I understand the concept of how they are made, the head and tail and how to add one (mostly), this may sound silly but how to you make the contents? I see how you make the first one, but how do u add more info. Heres an example of what I know.

Creating one


Code:
cpp
#include<iostream>
using namespace std;


typedef struct node // linked list structure
{
int data; // will store information
node *next; // the reference to the next node
};

node *temp= new node;

node *head = NULL; //empty linked list
node *tail = new node;



int main()
{
cout << "Please enter the number data ";
cin >> temp->data;

cout << temp->data;

temp->data=head;
temp->next=head;
head=temp;

cout << head;

system("pause");
return 0;

}

{some of this is wrong but how do u make more info. Like say i wanted the first node to be data=1 then the second node to be data =2 and 3 for the 3rd and so on until the last being Null. any suggestions??

Mod Edit: Please code.gif
Thanks, gabehabe smile.gif
User is offlineProfile CardPM
+Quote Post

Mallstrop
RE: Linked Lists
9 Jul, 2008 - 03:30 AM
Post #2

New D.I.C Head
*

Joined: 19 Jun, 2008
Posts: 32



Thanked: 1 times
My Contributions
Each node in the list holds a single piece of data along with a link to the next node in the chain.

To add a new item you need to create a new node, initialize it's data and then set the final node in the current list to link to the new node.

This code creates a new node (value of 5 and null (0) for next) and then finds the end of the list before placing it there.

Head is the first node in the list which seems a bit different from what you've used above.

You can also set the new node as Tail each time to save you having to traverse the list to find the end each time.


CODE

//Creating the new node
node *temp = new node;
temp->data = 5;
temp->next = 0;

//a Temp node used for traversing the list
node *current;
current = head;
    
//Finding the end of the list.
while (current->next != 0){
    current = current->next;
}
//Attaching the new node to the end.
current->next = temp;


This post has been edited by Mallstrop: 9 Jul, 2008 - 03:34 AM
User is offlineProfile CardPM
+Quote Post

Reply to this topicStart new topic
Time is now: 12/4/08 01:11PM

Live C++ Help!

C++ Tutorials

Reference Sheets

C++ Snippets

DIC Chatroom

Bye Bye Ads

Monthly Drawing

Thumb Drive

Top Contributors

Top 10 Kudos This Month