Open In App

How to Print Linked List in C++?

Last Updated : 23 May, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

A Linked List is a linear data structure that consists of nodes having a data member and a pointer to the next node. The linked list allows the users to store data of the same type in non-contiguous memory locations through dynamic memory allocation. In this article, we will learn how to print a linked list in C++.

Example

Input:
Linked List:
1->2->3->4->5

Output:
1 2 3 4 5

Print Linked List in C++

To print a linked list in C++, we can follow the below algorithm:

Algorithm to Print a Linked List

  • Start
  • Initialize a pointer temp to point at the head of the linked list.
  • While temp is not equal to nullptr:
    • Print temp->data.
    • Move temp to the next node using temp=temp->next.
  • Stop

C++ Program to Print a Linked List

The following program illustrates how we can print a linked list in C++:

C++
// C++ Program to demonstratre how to Print a Linked List
#include <iostream>
using namespace std;

// Node definition
class Node {
public:
    int data;
    Node* next;

    Node(int val)
    {
        data = val;
        next = nullptr;
    }
};

// Linked List definition
class LinkedList {
private:
    Node* head;

public:
    LinkedList() { head = nullptr; }

    // Function to add a node at the end of the list
    void insert(int val)
    {
        Node* newNode = new Node(val);
        if (head == nullptr) {
            head = newNode;
            return;
        }
        Node* temp = head;
        while (temp->next != nullptr) {
            temp = temp->next;
        }
        temp->next = newNode;
    }

    // Function to print the linked list
    void printList()
    {
        Node* temp = head;
        while (temp != nullptr) {
            cout << temp->data << " ";
            temp = temp->next;
        }
        cout << endl;
    }
};

int main()
{
    // Declare an object of the linked list class
    LinkedList list;
    // insert some values to the list
    list.insert(1);
    list.insert(2);
    list.insert(3);
    list.insert(4);
    list.insert(5);

    // Print the  linked list
    list.printList();

    return 0;
}

Output
1 2 3 4 5 

Time Complexity: O(N), where N is the number of nodes in the linked list.
Auxiliary Space: O(1), as no extra space is used to print the linked list.




Next Article
Article Tags :
Practice Tags :

Similar Reads