Evgenii Legotckoi
Evgenii LegotckoiApril 22, 2019, 2:13 a.m.

Linked list operations

This article is dedicated to the launch of the course "Algorithms for Developers" from OTUS. I express my gratitude for the support of the resource by this company.

Let's explore what operations can be performed on a linked list.

Two important points to remember:

  • head points to the first node of the linked list
  • next the last node pointer is nullptr , so if the next node from the current node is nullptr , we have reached the end of the linked list.

In all examples, we will assume that the linked list has three nodes 1 ---> 2 ---> 3 with a node structure as shown below:

struct node
{
    int data;
    struct node* next {nullptr};
};

How to iterate through a linked list

Displaying the contents of a linked list is very simple. We continue to move the temporary node to the next one and display its contents.

When temp is NULL , we know we've reached the end of the linked list, so we exit the while loop.

struct node* temp = head;
std::cout << std::endl << std::endl << "List elements are - " << std::endl;
while(temp != nullptr)
{
    std::cout << temp->data << " ---> ";
    temp = temp->next;
}

The output of this program will be:

List elements are - 
1 ---> 2 ---> 3 --->

How to add elements to a linked list

You can add elements to the beginning, middle, or end of a linked list.

Add to start

  • Allocate memory for the new node
  • Save data
  • Change the new next node to point to head
  • Change head to point to the newly created node
struct node* newNode = new node();
newNode->data = value;
newNode->next = head;
head = newNode;

Add to end

  • Allocate memory for the new node
  • Save data
  • Make a transition to the last node
  • Change next from last node to newly created node
struct node* newNode = new node();
newNode->data = value;
newNode->next = nullptr;

struct node *temp = head;
while (temp->next != nullptr)
{
    temp = temp->next;
}
temp->next = newNode;

Add to middle

  • Allocate memory and store data for the new node
  • Jump to the node immediately before the desired position of the new node
  • Change next pointers to add a new node in between
struct node *newNode = new node();
newNode->data = value;

struct node *temp = head;

for (int i=2; i < position; i++)
{
    if (temp->next != nullptr)
    {
        temp = temp->next;
    }
}
newNode->next = temp->next;
temp->next = newNode;

How to remove a node from a linked list

You can delete either from start, end or from a specific position.

Delete from beginning

  • Set the head pointer to the second node
head = head->next;

Delete from the end

  • Go to second last element
  • Change next pointer to nullptr
struct node* temp = head;
while (temp->next->next != nullptr)
{
    temp = temp->next;
}
temp->next = nullptr;

Remove from middle

  • Move to the element before the element to be removed
  • Change next pointers to exclude the node from the chain
struct node* temp = head;
for (int i = 2; i < position; ++i)
{
    if (temp->next != nullptr)
    {
        temp = temp->next;
    }
}

temp->next = temp->next->next;

Complete program for linked list operations

Here is the complete program for all the linked list operations we have learned. Many edge cases have been omitted to keep the program short.

We suggest you just take a look at the program and try to implement it yourself.

Also notice how we pass the address of head as struct node headRef in the insertAtFront and deleteFromFront functions. These two functions change the position of the head pointer, so we need to pass the address of the head** pointer and change its value inside the function.

#include <iostream>

struct node
{
  int data;
  struct node* next {nullptr};
};

void display(struct node* head)
{
    struct node* temp = head;
    std::cout << std::endl << std::endl << "List elements are - " << std::endl;
    while(temp != nullptr)
    {
        std::cout << temp->data << " ---> ";
        temp = temp->next;
    }
}

void insertAtMiddle(struct node *head, int position, int value)
{
    struct node *newNode = new node();
    newNode->data = value;

    struct node *temp = head;

    for (int i=2; i < position; i++)
    {
        if (temp->next != nullptr)
        {
            temp = temp->next;
        }
    }
    newNode->next = temp->next;
    temp->next = newNode;
}

void insertAtFront(struct node** headRef, int value)
{
    struct node* head = *headRef;

    struct node* newNode = new node();
    newNode->data = value;
    newNode->next = head;
    head = newNode;

    *headRef = head;
}

void insertAtEnd(struct node* head, int value)
{
    struct node* newNode = new node();
    newNode->data = value;
    newNode->next = nullptr;

    struct node *temp = head;
    while (temp->next != nullptr)
    {
        temp = temp->next;
    }
    temp->next = newNode;
}

void deleteFromFront(struct node** headRef)
{
    struct node* head =  *headRef;
    head = head->next;
    *headRef = head;
}

void deleteFromEnd(struct node* head)
{
    struct node* temp = head;
    while (temp->next->next != nullptr)
    {
      temp = temp->next;
    }
    temp->next = nullptr;
}

void deleteFromMiddle(struct node* head, int position)
{
    struct node* temp = head;
    for (int i = 2; i < position; ++i)
    {
        if (temp->next != nullptr)
        {
            temp = temp->next;
        }
    }

    temp->next = temp->next->next;
}

int main()
{
  /* Initialize nodes */
  struct node *head;
  struct node *one = new node();
  struct node *two = new node();
  struct node *three = new node();

  /* Assign data values */
  one->data = 1;
  two->data = 2;
  three->data = 3;

  /* Connect nodes */
  one->next = two;
  two->next = three;
  three->next = nullptr;

  /* Save address of first node in head */
  head = one;

  display(head); // 1 ---> 2 ---> 3 --->

  insertAtFront(&head, 4);
  display(head); // 4 ---> 1 ---> 2 ---> 3 --->

  deleteFromFront(&head);
  display(head); // 1 ---> 2 ---> 3 --->

  insertAtEnd(head, 5);
  display(head); // 1 ---> 2 ---> 3 ---> 5 --->

  deleteFromEnd(head);
  display(head); // 1 ---> 2 ---> 3 --->

  int position = 3;
  insertAtMiddle(head, position, 10);
  display(head); // 1 ---> 2 ---> 10 ---> 3 --->

  deleteFromMiddle(head, position);
  display(head); // 1 ---> 2 ---> 3 --->
}

The output of the program will be as follows

List elements are - 
1 ---> 2 ---> 3 ---> 

List elements are - 
4 ---> 1 ---> 2 ---> 3 ---> 

List elements are - 
1 ---> 2 ---> 3 ---> 

List elements are - 
1 ---> 2 ---> 3 ---> 5 ---> 

List elements are - 
1 ---> 2 ---> 3 ---> 

List elements are - 
1 ---> 2 ---> 10 ---> 3 ---> 

List elements are - 
1 ---> 2 ---> 3 --->

Conclusion

You can also study algorithms in more depth on the course "Algorithms for Developers" from OTUS you You will be able to study in more depth both basic algorithms and more complex ones.

The course offers the following:

  • Understanding the principles of operation of various algorithms, data structures
  • Ability to use ready-made algorithms and data structures and create your own for the task
  • Possession of the technique of calculating the complexity of algorithms
  • Mastering advanced data structures: hash tables, graphs, search trees and more
  • Ability to solve algebraic problems and dynamic programming problems

At the same time, this course offers the study of algorithms and data structures using such programming languages as Java, C ++, Python.

You can test your skills in testing to understand if you are ready to take this course and what this course will give you additionally.

We recommend hosting TIMEWEB
We recommend hosting TIMEWEB
Stable hosting, on which the social network EVILEG is located. For projects on Django we recommend VDS hosting.

Do you like it? Share on social networks!

Comments

Only authorized users can post comments.
Please, Log in or Sign up
AD

C ++ - Test 004. Pointers, Arrays and Loops

  • Result:50points,
  • Rating points-4
m

C ++ - Test 004. Pointers, Arrays and Loops

  • Result:80points,
  • Rating points4
m

C ++ - Test 004. Pointers, Arrays and Loops

  • Result:20points,
  • Rating points-10
Last comments
ИМ
Игорь МаксимовNov. 22, 2024, 10:51 p.m.
Django - Tutorial 017. Customize the login page to Django Добрый вечер Евгений! Я сделал себе авторизацию аналогичную вашей, все работает, кроме возврата к предидущей странице. Редеректит всегда на главную, хотя в логах сервера вижу запросы на правильн…
Evgenii Legotckoi
Evgenii LegotckoiNov. 1, 2024, 12:37 a.m.
Django - Lesson 064. How to write a Python Markdown extension Добрый день. Да, можно. Либо через такие же плагины, либо с постобработкой через python библиотеку Beautiful Soup
A
ALO1ZEOct. 19, 2024, 6:19 p.m.
Fb3 file reader on Qt Creator Подскажите как это запустить? Я не шарю в программировании и кодинге. Скачал и установаил Qt, но куча ошибок выдается и не запустить. А очень надо fb3 переконвертировать в html
ИМ
Игорь МаксимовOct. 5, 2024, 5:51 p.m.
Django - Lesson 064. How to write a Python Markdown extension Приветствую Евгений! У меня вопрос. Можно ли вставлять свои классы в разметку редактора markdown? Допустим имея стандартную разметку: <ul> <li></li> <li></l…
d
dblas5July 5, 2024, 9:02 p.m.
QML - Lesson 016. SQLite database and the working with it in QML Qt Здравствуйте, возникает такая проблема (я новичок): ApplicationWindow неизвестный элемент. (М300) для TextField и Button аналогично. Могу предположить, что из-за более новой верси…
Now discuss on the forum
m
moogoNov. 22, 2024, 6:17 p.m.
Mosquito Spray System Effective Mosquito Systems for Backyard | Eco-Friendly Misting Control Device & Repellent Spray - Moogo ; Upgrade your backyard with our mosquito-repellent device! Our misters conce…
Evgenii Legotckoi
Evgenii LegotckoiJune 25, 2024, 1:11 a.m.
добавить qlineseries в функции Я тут. Работы оень много. Отправил его в бан.
t
tonypeachey1Nov. 15, 2024, 5:04 p.m.
google domain [url=https://google.com/]domain[/url] domain [http://www.example.com link title]
NSProject
NSProjectJune 4, 2022, 1:49 p.m.
Всё ещё разбираюсь с кешем. В следствии прочтения данной статьи. Я принял для себя решение сделать кеширование свойств менеджера модели LikeDislike. И так как установка evileg_core для меня не была возможна, ибо он писался…

Follow us in social networks