JIYIK CN >

Current Location:Home > Learning > ALGORITHM >

Linked list reversal

Author:JIYIK Last Updated:2025/03/18 Views:

A linked list is a linear data structure. A node in a linked list consists of:

  • Data item.
  • The address of the next node.
class Node
{
    int data;
    Node *next;
};

Linked List

This article will show you how to reverse a linked list given a pointer to the head node of the linked list.

Linked list reversal algorithm

Let headbe the first node of the linked list.

Iterative Algorithm

  • Initialize 3 pointers - currset to head, prevand nextset to NULL.
  • Traverse the linked list until you reach the last node, which is curr!= NULLand do the following:
    • Set nextto curr->next 个to nextmove to its next node.
    • prevReverses the direction of the current node by pointing it toward . Therefore, curr->nextset to prev.
    • Set prevto currto move it forward one position.
    • Set currto nextto move it forward one position.

Recursive Algorithm

  • Split the list into two parts: the first node, the headnode, and the rest of the linked list.
  • Call reverse(head->next), i.e., the remainder of the reverse linked list, and store the reverse linked list as rev.
  • Append headto the end of the reverse-linked list rev.
  • Points to head, that is, the tail of the reverse link list points toNULL

Reverse Linked List using Stack

  • Initializes heada pointer to a linked list curr.
  • Traverse the linked list and insert each node one by one.
  • Update headto the last node in the linked list, which is the first node in the stack.
  • Start popping nodes from the stack one by one and appending it to the end of the reverse linked list.
  • Update the next pointer of the last node to NULL.

Linked list reversal diagram

Linked list reversal

  • Initialize currto point to the head, that is, nodes 2and , prevand currthe data of is NULL.
  • Sets nextto point to curr->nexta value equal to 4.
  • Set curr->nextto prevto obtain 2a list of backward links headed by .
  • Move prevto the node currwith data 2, and currmove to the node nextwith data .4
  • Points nextto curr->nexta value equal to6
  • Set curr->nextto prevto obtain a reverse linked list with 2and 4as reverse nodes and with 4as the head.
  • Move prevto , that is, the node currwith data , and move to , that is, the node with data . 4currnext6
  • Sets nextto point to curr->nexta value equal to 8.
  • Set curr->nextto prevto obtain a reverse linked list with and 2as reverse nodes and headed by . 466
  • Move prevto , that is, the node currwith data , and move to , that is, the node with data . 6currnext8
  • Point nextto curr->next, that is NULL.
  • Set curr->nextto prev, with 2, 4, 6and 8as reverse nodes and with 8as the head to obtain a reverse linked list.
  • Move prevto curr, that is, 8the node with data , move currto NULL, and the algorithm terminates.

Implementation of linked list reversal

#include <bits/stdc++.h>
using namespace std;

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

void printList(Node* head)
{
    Node*curr = head;
    while (curr != NULL) {
        cout << curr->data << " ";
        curr = curr->next;
    }
}

Node* reverse(Node* head)
{

    Node* curr = head;
    Node *prev = NULL, *next = NULL;

    while (curr != NULL) {
        next = curr->next;
        curr->next = prev;
        prev = curr;
        curr = next;
    }
    head = prev;
    return head;
}

Node* recursiveReverse(Node* head)
{
    if (head == NULL || head->next == NULL)
        return head;

    Node* rest = recursiveReverse(head->next);
    head->next->next = head;
    head->next = NULL;
    return rest;
}

void reverseLL(Node** head)
{

    stack<Node*> s;
    Node* temp = *head;
    while (temp->next != NULL)
    {
        s.push(temp);
        temp = temp->next;
    }
    *head = temp;

    while (!s.empty())
    {
        temp->next = s.top();
        s.pop();
        temp = temp->next;
    }
    temp->next = NULL;
}

int main()
{
    Node* head = new Node(1);
    head -> next = new Node(2);
    head -> next-> next = new Node(3);
    head -> next-> next-> next = new Node(4);
    head -> next-> next-> next-> next = new Node(5);
    head -> next-> next-> next-> next-> next = new Node(6);
    head = reverse(head);
    printList(head); cout << "\n";
    head = recursiveReverse(head);
    printList(head); cout << "\n";
    reverseLL(&head);
    printList(head); cout << "\n";
    return 0;
}

Linked list reversal algorithm complexity

Time Complexity

  • Average situation

To reverse a complete linked list, we have to visit each node and then append it to the reversal list. Therefore, if a linked list has nnodes, the average case time complexity of traversal is about O(n). The time complexity is about O(n).

  • Best Case

The time complexity of the best case is O(n). It is the same as the time complexity of the average case.

  • Worst case scenario

The worst case time complexity is O(n). It is the same as the best case time complexity.

Space complexity

The space complexity of this traversal algorithm is O(1), since no additional space is required except for the temporary pointers.

For reprinting, please send an email to 1244347461@qq.com for approval. After obtaining the author's consent, kindly include the source as a link.

Article URL:

Related Articles

Learning the Sorting Algorithm - Insertion Sort (Concepts)

Publish Date:2025/03/19 Views:96 Category:ALGORITHM

What is "insertion sort"? The concept is as follows: each time a record to be sorted is inserted into the previously sorted sequence according to its key size, until all records are inserted. Concepts are always somewhat abstract, and can a

Learning path of sorting algorithm - direct insertion sort

Publish Date:2025/03/19 Views:176 Category:ALGORITHM

This article follows up on Insertion Sort (Concepts) and presents the implementation steps and code for direct insertion sort. Since the Concepts section already has a large number of illustrations, it would be a bit long-winded to provide

Learning the sorting algorithm - Binary Insertion Sort

Publish Date:2025/03/19 Views:143 Category:ALGORITHM

This article follows the insertion sort (concept article) and presents the implementation steps and implementation code of the binary insertion sort Binary Insertion Sort Algorithm Steps Treat the first element of the first sequence to be s

The road to learning sorting algorithms - table insertion sort

Publish Date:2025/03/19 Views:194 Category:ALGORITHM

Table insertion sort was briefly mentioned in Insertion sort (concept) . I briefly summarized it and wrote this article. You can refer to it if you need it. Table insertion sort, as the name implies, uses an index table to sort the original

The road to learning sorting algorithms - Hill sort

Publish Date:2025/03/19 Views:52 Category:ALGORITHM

Hill sort is named after the designer of the algorithm, Hill. It is an improvement of Hill on the basis of insertion sort and can be said to be a special insertion sort. Here are the properties of insertion sort: First of all, the insertion

Things about the singleton design pattern

Publish Date:2025/03/19 Views:53 Category:ALGORITHM

The singleton design pattern is one of the most commonly used design patterns. The singleton design pattern, just by its name, you can roughly know its meaning. Single means one; instance means instance object. So a singleton has only one i

The road to learning sorting algorithms - merge sort

Publish Date:2025/03/19 Views:158 Category:ALGORITHM

Let's first look at the definition of merge sort Merge sort is an effective sorting algorithm based on the merge operation. This algorithm is a very typical application of the Divide and Conquer method. Merge the ordered subsequences to obt

The road to learning sorting algorithms - quick sort

Publish Date:2025/03/19 Views:122 Category:ALGORITHM

Quick sort is a sorting algorithm developed by Tony Hall. On average, sorting n items requires O(n log n) comparisons. In the worst case, O(n2) comparisons are required, but this is uncommon. In fact, quick sort is often significantly faste

Scan to Read All Tech Tutorials

Social Media
  • https://www.github.com/onmpw
  • qq:1244347461

Recommended

Tags

Scan the Code
Easier Access Tutorial