Singly Linked List in C++

A singly Linked List is the simplest linked list in which you can traverse the list only in one direction from head to the last node.


A Linked List is a linear data structure in which each element is stored in the form of a node and each node contains two parts, one part is to store the data and another part contains a pointer pointing to the next node (the pointer holds the address of the next node). 

Unlike an array, in linked list nodes are not stored at a contiguous memory location. All nodes are linked using pointers and form a linear structure. We use a head pointer that always points to the first node of the list and it is used to traverse the linked list. The last node of the list points to null that indicates the end of the list. 


List of Operations on Singly Linked List.

1. Creating a new List.

Create a class Node with two attributes one is data and the other one is a node. The data is used to store elements and the node is a pointer pointing to the next node.

class Node{
    public:
    int data;
    Node *next;
    //constructor
    Node(int data){
        this->data = data;
        this->next = NULL;
    }
};


As we are creating a completely new list it means there should be no address to store inside the head pointer so in that case, the head pointer points to null. Create a new node and the head node will store the address of the newly created node.


2. Adding a new node to the List.

We have three cases for adding a new node in a singly linked list. We can add a node at the front of the list, at the end of the list, or anywhere in the list. 
  • Adding a node at the front takes O(1) time complexity.
  • Adding a node at the end takes O(n) time complexity.
  • Adding a node anywhere in between takes O(n) time complexity. 
Read our post, Insertion in a Singly Linked List to understand the process of adding a new node in detail.

3. Search for a node in the list.

To search for a value in a linked list, we need to traverse the list to compare the value and in the worst case, it will take O(n) time. The below function will return true if the value is present in the list.
bool search(Node *head, int value){
    Node *current = head;
    //traverse list
    while(current != NULL){
        if(current->data == value)
           return true;
        current = current->next;   
    }
    return false;
}

4. Remove a node from the list.

We can remove a node from the front, end, or middle of the linked list and worst case it can take O(n) time complexity. Always remember to free the memory of the deleted node.


C++ Code Implementation of Singly Linked List.

//C++ Example of Singly Linked List
#include<iostream>
using namespace std;

class Node{
    public:
    int data;
    Node *next;
    //constructor
    Node(int data){
        this->data = data;
        this->next = NULL;
    }
};

//Add a node to the list
Node *addNode(Node *head, int data){

    Node *new_node = new Node(data);
    //add a new node when list is empty
    if(head == NULL)
      head = new_node;
    //adding new node at the front of the list  
    else{
        new_node->next = head;
        head = new_node;
    }
    return head;  
}

//Search a node in the list
bool search(Node *head, int value){
    Node *current = head;
    //traverse list
    while(current != NULL){
        if(current->data == value)
           return true;
        current = current->next;   
    }
    return false;
}
//Remove a node from the list
void deleteNode(Node* head, int position)
{
    Node* temp;
    Node* prev;
    temp = head;
    prev = head;
    for (int i = 0; i < position; i++) {
        if (i == 0 && position == 1) {
            head = head->next;
            free(temp);
        }
        else {
            if (i == position - 1 && temp) {
                prev->next = temp->next;
                free(temp);
            }
            else {
                prev = temp;
 
                // Position was greater than
                // number of nodes in the list
                if (prev == NULL)
                    break;
                temp = temp->next;
            }
        }
    }
}
//Traversing Linked List
void display(Node *head){
    Node *temp = head;

    while(temp != NULL){
        cout<<temp->data<<" ";
        temp = temp->next;
    }
}

int main(){
    Node *head = new Node(32);
    head = addNode(head, 20);
    head = addNode(head, 40);
    head = addNode(head, 12);

    cout<<"Singly Linked List: ";
    display(head);
    
    if(search(head, 20))
      cout<<"\nValue is present in the List";
    else
      cout<<"\nValue is not present in the List";

    deleteNode(head, 2);

    cout<<"\nSingly Linked List after deletion: ";
    display(head);

    return 0;    
}
Output:
Singly Linked List: 12 40 20 32
Value is present in the List
Singly Linked List after deletion: 12 20 32

Signed and Unsigned Types in C++

Signed and Unsigned are datatype modifiers which mostly use with integral type values to tell us about the sign of that value whether the value is a positive value or negative value. 

  • Signed type is used to represent negative or positive numbers including zero. The datatype like int, short, long, and long long are all signed values by default. Example: singed int x = -1; 
  • The Unsigned type is used to represent only values greater than or equal to zero. You can obtain the corresponding unsigned datatype by adding an unsigned keyword with the datatype. Example: unsigned int x = 4;

Note: Signed values have dedicated extra bits for storing the sign of the value. 


Let's understand with one C++ example code of signed and unsigned values.

//C++ Example for signed and unsigned values
#include<iostream>
using namespace std;

int main(){

  unsigned int num = -1;
  int x = -1;

  cout<<num<<","<<x;
  return 0;
}
Output:
4294967295,-1

In the above code, you can observe that when we try to store a negative value in an unsigned variable then in the output it is printing some random value, and the integer variable which is by default a signed variable can easily store a negative number.
When you try to store any negative value in an unsigned variable then that variable actually stores the 2's complement of the binary equivalent of that value. The 2's complement of -1 in 32-bit format will be equal to 4294967296 and that same value is printed in the output. (alert-success)

Basic Character Types

Unlike the other integer types, there are three distinct basic character types:

  • char
  • signed char
  • unsigned char 
Although there are three character types, there are only two representations and these are signed and unsigned. The char type uses one of these representations and it depends upon the compiler. 

Type Conversion in C++

The data type of any variable tells us about the value you can store in that variable and what operations you can perform on it. It might be possible that one operation is supported by more than one data type and to handle such cases C++ allows us to convert one datatype to another datatype. This process of converting data type is known as Type Conversion or Type Casting.


In C++, there are two types of Type Conversion:

  • Implicit Type Conversion.
  • Explicit Type Conversion.


Implicit Type Conversion in C++.

Implicit type conversion is done automatically by the compiler wherever it is required in the program. It takes place when more than one data type is present in an expression. 

Let's understand with some examples of implicit type conversion. 

//Example of Implicit Type Conversion
#include<iostream>
using namespace std;

int main(){

  //conversion of int to bool type
  int value = 25;
  bool check = value;

  cout<<check<<endl;

  //conversion of double to int
  double pi = 3.14;
  int i = pi;

  cout<<i<<endl;

  //conversion of signed to unsigned
  unsigned int num = -1;

  cout<<num<<endl;

  return 0;
}
Output:
1
3
4294967295

We have observed the following points from the above example:
  • When we assign one of the non-boolean arithmetic types to a boolean object, the result is false if the value is 0 and true otherwise. 
  • When we assign a boolean to one of the arithmetic types, the result value is 1 if the boolean is true and 0 if the boolean is false. 
  • When we assign a floating-point value to an object of integral type, the value is truncated. It means the value before the decimal point will get stored. 
  • When we assign an integral value to a floating type then the fraction part is zero. 
  • When we assign a signed value to an unsigned value then it stores 2's complement of the value. 

You will observe from the above code that there is a chance of losing information in implicit type conversion. For example, when we try to store a floating value in an integer value we lose the value present after the decimal point. This usually happens when data of a larger type get converted to a smaller type. 

You can follow the below chart to check the Data Lose During Type Conversion.
  
Type Conversion Chart
Data Lose During Type Conversion

Explicit Type Conversion in C++.

In Explicit Type Conversion user manually change the data type from one type to another type based on the requirement. This process is also known as Type Casting. 

There are multiple ways for performing Explicit type conversion and here we are going to discuss them one by one.
  • Forceful Casting: In this type of casting you explicitly define the required datatype in front of the expression. 
syntax: (data_type) expression; 

//Example of Explicit Type Conversion
#include<iostream>
using namespace std;

int main(){

  float x = 3.14;

  int ans = (int)x * 4 * 4;
  cout<<ans<<endl;

  return 0;
}
Output:
48

Type Conversion Operators

C++ have four operators for performing type casting and they are:
  • Static cast
  • Dynamic cast
  • Const cast
  • Reinterpret cast
Example:
//C++ Example of Operator Type Conversion
#include<iostream>
using namespace std;

int main(){

  float x = 3.14;

  int ans = static_cast<int>(x);
  cout<<ans<<endl;

  return 0;
}
Output:
3

Data Types in C++.

Data Types are one of the most essential topics of any programming language that you should understand whenever you are learning any new programming language. The data type can be defined as which type of value a variable can store and what kind of mathematical, logical, and relational operations are allowed on those values.

In C++ programming, data types can be classified into the following groups:
  • Primitive/Built-in Datatypes.
  • Derived Datatypes.
  • User-Defined Datatypes.
data type in C++
There are several data types available in the C++ programming language.

Primitive Datatypes in C++.

Primitive data types are built-in datatypes that are already available to use in C++ programming languages. There are 7 primitive data types available in C++ programming and these are integers, float, double, character, boolean, void, and wide character. 

1. Integer
An integer data type is represented by the int keyword in C++  and each integer value takes up to 4 bytes of memory. The range of an integer-type variable is -2147483648 to 2147483647, this is the minimum and maximum value that you can store in an integer-type variable. Example: int num = 3450;

2. Floating point
A floating point data type is represented by the float keyword in C++ and is used to store decimals and exponential values. Each floating point value requires 4 bytes of memory. Example: float value = 45.15;

3. Double
Like floating data, Double data types are also used to store decimals and exponential values but double requires 8 bytes of memory because the precision of double is greater than float. Example: double value = 45.1502;

4. Boolean
Boolean datatype is represented by the bool keyword in C++ and can store only two types of values 'true' or 'false'. Example bool check = true;

5. Character
Character datatype is represented by the char keyword in C++ and requires 1 byte of memory. Characters are enclosed inside single quotes(' ') in C++. Example: char ch = 'a';

6. void
The term void means "no value" or "nothing", it is the keyword that is used to indicate the absence of data. There is no variable of type void, it is only used with those function which does not return any value.

7. Wide Character
Wide character (wchar_t) is the same as character data type but unlike char, it takes 2 or more bytes and is used to represent the character that requires more memory. Example: wchar_t w = L'A' 

Derived data types in C++

The data types that are derived from primitive or built-in data types are known as Derived Datatype. 

1. Function
A function is a block of code with a set of instructions that is used to perform a specific task. We create functions to avoid writing the same lines of code again and again. We can call the function anywhere inside the code whenever we want to perform that same task. 

Example: This function is used to perform the addition of two numbers and return a result of type integer.  
int sum(int a, int b){
  return (a + b);
}

2. Array
An array is a Linear Data Structure that can store elements of similar data types in a contiguous memory location. The main use of an Array is to store many values in just one variable. 
syntax: data_type ArrayName[size_of_array];

Example: int arr[5] = {2, 4, 6, 7, 1};

3. Pointers
A pointer is a variable that is used to hold the address of another variable. It stores the address of the variable having the same data type (integer pointer can hold the address of integer type variable). Example: int *ptr;

4. Reference
Reference is like an alternative name for another existing variable. It is represented by putting the '&' symbol in front of any variable. Example: int &ref = num;


User-Defined data types in C++

User-defined datatypes are created by users based on their requirements and they are created by using existing built-in data types.

1. Class
Class is a user-defined data type that has its own data members and member functions. It is a very important concept of object-oriented programming in C++. 
//Example of C++ class program
#include<iostream>
using namespace std;

class Addition{
  public:
  int result; //data member

  void add(int x, int y){ //member function
    result = x + y;
    cout<<"Result: "<<result;
  }
};

int main(){
  Addition obj;
  obj.add(5, 10);
  return 0;
}
Output:
Result: 15

2. Structure
A structure is a user-defined data type that is used to combine different data types into a single type. It is represented using the struct keyword in C++.
//Example of C++ structure program
#include<iostream>
using namespace std;

struct student{
  int rollNo;
  string name;
  char grade;
};

int main(){
  student std;
  std.rollNo = 10;
  std.name = "John";
  std.grade = 'A';

  cout<<std.name<<endl;
  cout<<std.rollNo<<endl;
  cout<<std.grade<<endl;

  return 0;
}
Output:
John
10
A

3. Enumeration
Enumeration is a user-defined data type denoted by an enum keyword in C++ and mainly use to assign names to integral constants.
//Example of C++ program to demonstrate enum
#include<iostream>
using namespace std;

enum week{
  Sunday,
  Monday,
  Tuesday,
  WednesDay,
  Thursday,
  Friday,
  Saturday
};

int main(){
  enum week day;
  day = Sunday;
  
  cout<<day;

  return 0;
}
Output:
0

4. Union
Union and Structure in C++ have almost the same features and both are user-defined data types. The only difference between them is that Union shares the same memory location. 
Example: Any change you will made in value x will be reflected in value y.
union test{
  int x, y;
};

5. Typedef
Typedef is used to explicitly define any new name to our existing data type. Example:
typedef long int ll;
ll num = 3439;


Datatype Modifiers in C++

A modifier is used to change the basic meaning of our built-in data types like int, float, double, and char so they fit precisely in various situations. There are four types of modifiers available in C++ and these are short, long, signed, and unsigned

Below is the list of datatypes and the amount of memory they required with the range of values that particular datatypes allow. 

Data Type Memory Size Range
int 4 Bytes -2,147,483,648 to 2,147,483,647
signed int 4 Bytes -2,147,483,648 to 2,147,483,647
unsigned int 4 Bytes 0 to 4,294,967,295
short int 2 Bytes -32,768 to 32,767
unsigned short int 2 Bytes 0 to 65,535
unsigned long int 8 Bytes 0 to 4,294,967,295
long long int 8 Bytes -(2^63) to (2^63)-1
unsigned long int 8 Bytes 0 to 4,294,967,295
unsigned long long int 8 Bytes 0 to 18,446,744,073,709,551,615
signed char 1 Byte -128 to 127
unsigned char 1 Byte 0 to 255
wchar_t 2 Bytes or 4 Bytes 1 Wide Character
float 4 Bytes
double 4 Bytes
long double 12 Bytes

Escape Sequences in C++

Characters such as backspace or control characters have no visible image and they are nonprintable. Other characters (like single or double quotation marks question marks and backslash) have special meanings in the programming language and you cannot use any of these characters directly. Instead, you need to use an escape sequence to represent such characters.


An Escape Sequence begins with backslash (\) followed by a character or by a combination of digits. 


There are several escape sequences are defined in C++ programming language such as:

Escape Sequence Character Represented
\n New Line
\t Horizontal Tab
\b Backspace
\" Double quote
\' Single quote
\? Question Mark
\r Carriage Return
\a Alert (bell)
\\ Backslash
\f Form feed (new page)

C++ Example of Escape Sequences.
//Example of C++ Escape Sequence
#include<iostream>
using namespace std;

int main()
{
  cout<<"This is an example of \'single quotes\' and \"double quotes\"";
  cout<<"\nThis is an example of newline and \\backslash";
  cout<<"\nThis is an example of \t Horizontal tab and a\bbackspace";
  
  return 0;
}
Output:
This is an example of 'single quotes' and "double quotes"
This is an example of newline and \backslash
This is an example of    Horizontal tab and backspace

Conclusion:

Escape sequences in C++ are special character combinations that are used to represent characters that are difficult or impossible to type directly in a string or character literal. They begin with a backslash (\) followed by a specific character or sequence of characters.

Next:

Variables, Constant and Literals in C++

In this article, we will discuss variables, constants, and literals in C++ programming language with examples.


C++ Variables

In programming, variables are containers for storing data values. It is basically a name given to a memory location and this name must be unique, you cannot use the same variable name for two different memory locations. The value that you will store in a variable can be changed during the execution of the program. 

syntax: data_type variable_name;
example: int count = 10;
variables in C++
Variables in C++
Rules for deciding a variable name:
  • A variable name can contain only alphabets, digits, and underscores. 
  • A variable name must begin with an alphabet or underscore, it cannot begin with a number.
  • A variable name should not contain any whitespace or special characters like #, $, @, %, *, etc.
  • A variable name is case-sensitive in nature. Ex: num and Num is two different variables.
  • One cannot use C++ reverse keywords (Ex: int, float, for) as a variable name. 
Note: It is suggested to start a variable name with lowercase alphabets and try to give always meaningful variable names. (alert-success)


C++ Constant

In C++ programming, constants are those kinds of variables whose values are fixed and cannot be changed. These kinds of variables are defined using the const keyword and they have read-only property. Example: 

const float PI = 3.14
PI = 3.141 //Error: value of PI is constant

C++ Literals

Values such as numbers, characters, or strings of characters whose values are self-evident are known as literals. These values you can use directly in your C++ code. Example: 4, 5.6, 'c', 3.14156e3, 0x19, etc. 

Different kinds of literals present in C++ programming:

1. Integer Literals: Integer literals are those numbers that do not have any decimal point or exponential part. We can write an integer literal using decimal, octal or hexadecimal notation.
  • Decimal (base 10): It is the Normal representation of numbers that we use in daily life. Ex: 25
  • Octal (base 8): Integer literals that begin with 0 are interpreted as octal. Ex: 031 is an octal representation of 25.
  • Hexadecimal (base 16): Integer literals that begin with 0x or 0X are interpreted as hexadecimal. Ex: 0x19 is a hexadecimal representation of 25.
//C++ example of Integer Literals
#include<iostream>
using namespace std;

int main()
{
    int x, y, z;
    x = 25;
    y = 031;
    z = 0x19;

    cout<<"Decimal Representation: "<<x<<endl;
    cout<<"Octal Representation: "<<y<<endl;
    cout<<"Hexadecimal Representation: "<<z<<endl;

    return 0;
}
Output:
Decimal Representation: 25
Octal Representation: 25
Hexadecimal Representation: 25

In the above code, you can observe that all three different integer variables represent the same value 25 in C++ programming.

2. Floating point Literals: Floating-point literals include either a decimal point or an exponent (indicated by either E or e) that is specified using scientific notation. 
Example:
3.52341
3.52341E2 = 3.52341x10^2 = 352.341
3.52341e2 = 3.52341x10^2 = 352.341
3.52341E-1 = 3.52341x10^-1 = 0.352341

//C++ example of Floating Point Literals
#include<iostream>
using namespace std;

int main()
{
    float x, y, z, n;
    x = 3.52341;
    y = 3.52341E2;
    z = 3.52341e3;
    n = 3.52341E-1;

    cout<<x<<endl;
    cout<<y<<endl;
    cout<<z<<endl;
    cout<<n<<endl;

    return 0;
}
Output:
3.52341
352.341
3523.41
0.352341
  
3. Character Literals: A character enclosed with single quotes are known as a character literal. Ex: 'a', '4', '{', etc.

4. String Literals: When zero or more characters are enclosed in double quotation marks is known as a string literal. Ex: "fruit", "code", " ", "c", "\nHello World", etc.
Note: The compiler appends a null character ('\0') to every string literal. Thus, the actual size of a string literal is one more than its apparent size. (alert-success)
You can read our article, character vs string class in C++ to understand the difference between them.

Using Namespace in C++.

If you are already familiar with C++ programming then you must have seen this line "using namespace std" on top of the code after including all required header files. Many beginners consider this as a part of C++ syntax without trying to understand its exact meaning. In this article, we will discuss namespace and why we use it.


What is Namespace in  C++?

A namespace is a declarative region that provides a scope to the identity functions or variables inside it. They are used to organize code into logic groups and prevent name collisions, mainly when the code base includes multiple libraries. 


Let's understand it using one example condition: 

#include<iostream>

int main()
{
    int n = 0;
    std::cout<<"Enter a number: ";
    std::cin>>n;
    std::cout<<"The entered number is: " << n;
    return 0;
}
Output:
Enter a number: 5
The entered number is: 5

In the above example code, we have used std::cout and std::cin instead of simply using cout and cin. The prefix std:: indicates that the name cout and cin are defined inside the namespace named std which stands for "standard library".

A using-declaration lets you use a name from a namespace without qualifying the name with a namespace_name::prefix. 
  • syntax: using namespace::name;
C++ Example code:
#include<iostream>
using std::cin;
using std::cout;

int main()
{
    int n = 0;
    cout<<"Enter a number: ";
    cin>>n;
    cout<<"The entered number is: " << n;
    return 0;
}
Output:
Enter a number: 5
The entered number is: 5

In the above code example, you will notice that we are using cout and cin without std:: because we have already defined that we are using cin and cout from the std namespace so we don't have to write std:: again, and again.

C++ using namespace std Example.

using namespace std in C++ code indicates that any name that we are going to use in our code belongs to the std (standard library) namespace. It is mainly used for our input/output operations.
#include<iostream>
using namespace std;

int main()
{
    int n = 0;
    cout<<"Enter a number: ";
    cin>>n;
    cout<<"The entered number is: " << n;
    return 0;
}
Output:
Enter a number: 5
The entered number is: 5
 

DON'T MISS

Tech News
© all rights reserved
made with by AlgoLesson