ArtsAutosBooksBusinessEducationEntertainmentFamilyFashionFoodGamesGenderHealthHolidaysHomeHubPagesPersonal FinancePetsPoliticsReligionSportsTechnologyTravel
  • »
  • Technology»
  • Computers & Software»
  • Computer Science & Programming

Linked List Codes in C++

Updated on January 1, 2016
alikhan3 profile image

The Author is a proud Nustian where he studies Electrical Engg. at Pakistan Navy Engineering College, Karachi.

This article is going to guide you through the entire process of how singly linked lists work. C++ codes for 7 basic functions of a linked list are given along with some explanation in the following order:

  1. Initial Declarations
  2. The Main function
  3. Function to add a new record in linked list.
  4. Listing all records.
  5. Delete a record.
  6. Update an existing record.
  7. Insert a new record in middle of the list.

So lets first have a look at the initial declarations required for every linked list.

1. Initial Declarations for a Linked list

#include <iostream>
#include <conio.h>
#include <string>
#include <cstdlib>

#define TRUE 1

using namespace std;

void newname ( void ); //Creates a new record at the end of the list.
void listall ( void ); //Lists the items of the list.
void addItem ( void ); //Adds a new record to list.
void delItem ( void ); //Deletes an existing record.
void TempNode( void ); //Creates a new node.
void Updation( void ); //Updates an existing record of list.

struct prs
{
	char name [31];
	int agnumb;
	double height;
	struct prs *ptrnext;
}; 

struct prs *ptrfirst, *ptrthis, *ptrnew;
struct prs *ptrtemp, *ptrtemp2;

Before we proceed further I want you to get familiar with a few basic things we will be using throughout our explanation.

Line 17-23: This is a structure (make sure you have understood this from your books before proceeding further). It will serve as a basic template for data entry in our list.

Line 25-26: Five variables which are essentially 'pointers to this structure' are initialized.

Summary of Variables Used

(click column header to sort results)
Pointer Variable  
Usage in List  
ptrfirst
It will always point to the first record in list.
ptrthis
It can point to any record in the list. Generally we will use loops with this pointer to make it point to our desired record
ptrnew
Whenever a new record is created, it will be used to point to it.
ptrtemp and ptrtemp2
will be used to temporarily store the address of any desired record.
ptrnext
This was declared inside the structure definition in Line 22. It is used to link a record wih its subsequent record by storing its address as it is alos a pointer variable.
Summary of Important pointer variables used in this code.

Pointer Notation in C++

ptrthis->ptrnext = ptrnew;

All of the variables declared above are essentially pointers to structures as I mentioned earlier such that they store addressees of memory locations where these structure are stored. Now this pointer notation should be read from right to left meaning that The address of ptrnew will be stored in ptrnext of ptrthis. Where ptrnext is itself a pointer declared as variable inside the structure towards which ptrthis points. Now I hope that I am clear enough and if you learn to interpret it this way it will be a lot easier to get hold of it.

2. The Main Function

int main( void )
{
    char ch;
    ptrfirst = static_cast <struct prs*> (NULL);
    while( TRUE )
    {
        cout<<"\nTYPE [E] TO ENTER NEW AGENT:";
        cout<<"\nTYPE [L] TO LIST ALL AGENTS:";
        cout<<"\nTYPE [N] TO ADD TO LIST:";
        cout<<"\nTYPE [D] TO DELETE ANY ITEM:";
        cout<<"\nTYPE [U] TO UPDATE LIST:";
        cout<<"\nTYPE [Q] TO QUIT:";
        cout<<"\nYOU ENTERED:";
        ch = getche();
        cout<<endl;
        
        switch( ch )
	    {
            case 'E':
            newname();
	        break;
	        
	        case 'L':
	        listall();
            break;
            
            case 'N':
            addItem();
            break;
            
            case 'D':
            delItem();
            break;
            
            case 'U':
            Updation();
            break;
            
	        case 'Q':
            exit(0);
            
            
            default:
            cout<<"\nENTER ONLY THE LISTED SELECTIONS";
            cout<<endl;
         }
     }
}

Line 4: Makes ptrfirst a null pointer (the address zero is stored in it).

Line 5: A while loop is initiated whose condition is always true meaning it will run until the user asks to quit.

Line 7-15: The menu of the list is displayed asking the user to pick a choice out of the available functions by pressing a character.

Line 17-46: The switch statement invokes the desired function of the user according to the character pressed.

3. Adding a New Record in Linked List

void newname( void )
{
    char numstr [81];
    ptrnew = ( struct prs* ) malloc( sizeof( struct prs ) );
    if( ptrfirst == ( struct prs* )NULL )
    {
        ptrfirst = ptrthis = ptrnew;
	}
    else
	{
        ptrthis = ptrfirst;
        while( ptrthis->ptrnext != (struct prs*) NULL )
		{
            ptrthis = ptrthis->ptrnext;
        }
		ptrthis->ptrnext = ptrnew;
		ptrthis = ptrnew;
    }
    
	cout<<"\nENTER NAME:";
	cin.getline( ptrthis->name, 30,'\n');
	
	cout<<"\nENTER NUMBER:";
	cin>>ptrthis->agnumb;
	
	cout<<"\nENTER HEIGHT:";
	cin>>ptrthis->height;
    
	ptrthis->ptrnext =( struct prs* )NULL;
}

Line 4: This is dynamic memory allocation. In this statement firstly the sizeof operator determines the size in bytes of the variable prs then malloc allocates this memory for the record. The parenthesis left of malloc 'type casts' the address of this allocated memory and saves it into ptrnew.

Essentially all of this could be achieved much more easily using the C++ operator new in the following way:

ptrnew = new( prs );

Line 4-18: Execution of these lines along with memory simulation is explained in the video below. Watch the video at least three times in full screen and I am sure you will get hold of it. (Please report any issues if you have with this video).

Line 20-27: These lines ask the user to input data.

4. Listing Records of the Linked List

void listall( void )
{
	if( ptrfirst == ( struct prs* ) NULL )
	{
		cout<<"\nEMPTY LIST\n";
        return;
    }
	ptrthis = ptrfirst;
	do
	{
		cout<<"\nNAME: "<<ptrthis->name;
		cout<<"\nNUMBER: "<<ptrthis->agnumb;
		cout<<"\nHEIGHT: "<<ptrthis->height;
        cout<<endl;
		ptrthis = ptrthis->ptrnext;
	}
	while( ptrthis !=( struct prs* ) NULL );
}

This function lists all the records that were previously entered by the user or in other words it just displays the data of the whole list.

Line 3-7: If there are no records entered this if condition will become true and "Empty list" will be displayed. If their are no records entered ptrfirst will be a null pointer.

Line 8: Address of ptrfirst is stored in ptrthis, now both of these pointers point towards the first record.

Line 11-13: Data members are displayed using cout inside a do while loop.

Line 15: When all the data members of a record have been displayed this line executes and it makes ptrthis point to the next record of the list so that when the loop runs again data members of the next record re displayed.

Line 17: The do while loop will continue until it reaches the last record where ptrthis will be Null.

5. Deleting an Existing Record from Linked List

void delItem( void )
{
     int a;
     cout<<"Enter Record Number to delete: ";
     cin>>a;
     
     if ( a == 1 )
     {
          ptrtemp = ptrfirst;
          ptrfirst = ptrfirst -> ptrnext;
          delete( ptrtemp );
     }
     else
     {
         ptrthis = ptrfirst;
         for ( int i=2 ; i<a ;i++ )
         {
             ptrthis = ptrthis -> ptrnext;
         }
         ptrtemp = ptrthis;
         ptrtemp2 = ptrtemp -> ptrnext;
         ptrtemp -> ptrnext = ptrtemp2 -> ptrnext;
         delete( ptrtemp2 );
     }
}

6. Updating an Existing Record in Linked List

void Updation( void )
{
	int a;
	cout<<"Enter Record to Update: ";
	cin>>a;
	
	if( a==1 )
	{
        TempNode();    
		ptrthis = ptrfirst;
		ptrtemp -> ptrnext = ptrthis -> ptrnext;
        ptrfirst = ptrtemp; 
	}
	else
	{
		ptrthis = ptrfirst;
		for ( int i=2 ; i<=a ; i++ )
		{
			ptrthis = ptrthis -> ptrnext;
        }
        cout<<"\nENTER NAME:";
        cin.getline( ptrthis->name, 30,'\n');
        cout<<endl;
	
        cout<<"\nENTER NUMBER:";
        cin>>ptrthis -> agnumb;
	 
        cout<<"\nENTER HEIGHT:";
        cin>>ptrthis->height;
	}
}

This function creates a temporary node for update function

void TempNode ()
{
     char numstr [81];
     ptrtemp = ( struct prs* ) malloc( sizeof( struct prs ) );
          
     cout<<"\nENTER NAME:";
     cin.getline( ptrtemp->name, 30,'\n');
     cout<<endl;
	
     cout<<"\nENTER NUMBER:";
     cin>>ptrtemp -> agnumb;
	
     cout<<"\nENTER HEIGHT:";
     cin>>ptrtemp->height;
     
}

Inserting a new record in Linked list

void addItem ( void )
{
     int a;
     cout<<"Enter Record Position: ";
     cin>>a;
     
     TempNode();
     
     if ( a == 1 )
     {
          
          ptrtemp -> ptrnext = ptrfirst;
          ptrfirst = ptrtemp;
     }
     else
     {
         ptrthis = ptrfirst;
         for (int i=2 ; i<a ; i++ )
         {
             ptrthis = ptrthis -> ptrnext;
         }
         ptrtemp->ptrnext = ptrthis->ptrnext;
         ptrthis->ptrnext = ptrtemp;
     }
}

© 2014 StormsHalted

Comments

    0 of 8192 characters used
    Post Comment

    No comments yet.

    working

    This website uses cookies

    As a user in the EEA, your approval is needed on a few things. To provide a better website experience, hubpages.com uses cookies (and other similar technologies) and may collect, process, and share personal data. Please choose which areas of our service you consent to our doing so.

    For more information on managing or withdrawing consents and how we handle data, visit our Privacy Policy at: "https://hubpages.com/privacy-policy#gdpr"

    Show Details
    Necessary
    HubPages Device IDThis is used to identify particular browsers or devices when the access the service, and is used for security reasons.
    LoginThis is necessary to sign in to the HubPages Service.
    Google RecaptchaThis is used to prevent bots and spam. (Privacy Policy)
    AkismetThis is used to detect comment spam. (Privacy Policy)
    HubPages Google AnalyticsThis is used to provide data on traffic to our website, all personally identifyable data is anonymized. (Privacy Policy)
    HubPages Traffic PixelThis is used to collect data on traffic to articles and other pages on our site. Unless you are signed in to a HubPages account, all personally identifiable information is anonymized.
    Amazon Web ServicesThis is a cloud services platform that we used to host our service. (Privacy Policy)
    CloudflareThis is a cloud CDN service that we use to efficiently deliver files required for our service to operate such as javascript, cascading style sheets, images, and videos. (Privacy Policy)
    Google Hosted LibrariesJavascript software libraries such as jQuery are loaded at endpoints on the googleapis.com or gstatic.com domains, for performance and efficiency reasons. (Privacy Policy)
    Features
    Google Custom SearchThis is feature allows you to search the site. (Privacy Policy)
    Google MapsSome articles have Google Maps embedded in them. (Privacy Policy)
    Google ChartsThis is used to display charts and graphs on articles and the author center. (Privacy Policy)
    Google AdSense Host APIThis service allows you to sign up for or associate a Google AdSense account with HubPages, so that you can earn money from ads on your articles. No data is shared unless you engage with this feature. (Privacy Policy)
    Google YouTubeSome articles have YouTube videos embedded in them. (Privacy Policy)
    VimeoSome articles have Vimeo videos embedded in them. (Privacy Policy)
    PaypalThis is used for a registered author who enrolls in the HubPages Earnings program and requests to be paid via PayPal. No data is shared with Paypal unless you engage with this feature. (Privacy Policy)
    Facebook LoginYou can use this to streamline signing up for, or signing in to your Hubpages account. No data is shared with Facebook unless you engage with this feature. (Privacy Policy)
    MavenThis supports the Maven widget and search functionality. (Privacy Policy)
    Marketing
    Google AdSenseThis is an ad network. (Privacy Policy)
    Google DoubleClickGoogle provides ad serving technology and runs an ad network. (Privacy Policy)
    Index ExchangeThis is an ad network. (Privacy Policy)
    SovrnThis is an ad network. (Privacy Policy)
    Facebook AdsThis is an ad network. (Privacy Policy)
    Amazon Unified Ad MarketplaceThis is an ad network. (Privacy Policy)
    AppNexusThis is an ad network. (Privacy Policy)
    OpenxThis is an ad network. (Privacy Policy)
    Rubicon ProjectThis is an ad network. (Privacy Policy)
    TripleLiftThis is an ad network. (Privacy Policy)
    Say MediaWe partner with Say Media to deliver ad campaigns on our sites. (Privacy Policy)
    Remarketing PixelsWe may use remarketing pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to advertise the HubPages Service to people that have visited our sites.
    Conversion Tracking PixelsWe may use conversion tracking pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to identify when an advertisement has successfully resulted in the desired action, such as signing up for the HubPages Service or publishing an article on the HubPages Service.
    Statistics
    Author Google AnalyticsThis is used to provide traffic data and reports to the authors of articles on the HubPages Service. (Privacy Policy)
    ComscoreComScore is a media measurement and analytics company providing marketing data and analytics to enterprises, media and advertising agencies, and publishers. Non-consent will result in ComScore only processing obfuscated personal data. (Privacy Policy)
    Amazon Tracking PixelSome articles display amazon products as part of the Amazon Affiliate program, this pixel provides traffic statistics for those products (Privacy Policy)