Subscribe to Invariance_Under_Translation        RSS Feed
-----

Linked List

Icon Leave Comment
I have recently been experimenting with Linked Lists. The code being posted below is very simple, but demonstrates how one might create a Linked List and utilize a very basic implementation. Enjoy and happy coding.

//Linked List
#include<iostream>

using namespace std;


struct Node
{
	int val;	//variable value in each node
	Node *next;  //pointer to next node

}*q;			//pointer to currect node


int main()
{
	Node *p, *t;	//create pointers to node
	int num;
	int loopCount = 0;

	cout<<"Enter five numbers for your linked list."<<endl;
	while(loopCount!=5)
	{
		loopCount++;
		cin>>num;
		cout<<endl;
	
		if(q == NULL)	//If current node does not contain a value...
		{
			q = new Node;	//dynamically allocate memory for the node
			q->val = num;	//point num value to node
			q->next = NULL;	//Set next node to NULL
		}
		else				//If current node contains a value
		{
			p = q;			//point p to current node
			while(p->next!=NULL)	//traverse node until next node is NULL
			p = p->next;		
			
			t = new Node;	//Once next node is NULL, create new node
			t->val = num;	//point num value to node
			t->next = NULL;	//set next node to NULL
			p->next = t;	//set p to current node
		}
	}

	cout<<"Here is your linked list"<<endl;

	for(p = q; p != NULL; p = p->next) //travers node, printing out num values. 
	{
		cout<<p->val<<endl;
	}
			
	cin.get();

	return 0;

}

0 Comments On This Entry

 

Trackbacks for this entry [ Trackback URL ]

There are no Trackbacks for this entry

July 2018

S M T W T F S
1234567
891011121314
15161718 19 2021
22232425262728
293031    

Tags

Recent Entries

Recent Comments

Search My Blog

0 user(s) viewing

0 Guests
0 member(s)
0 anonymous member(s)