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.