Open In App

Self Organizing List : Transpose Method

Improve
Improve
Like Article
Like
Save
Share
Report

Self Organizing list is a list that re-organizes or re-arranges itself for better performance. In a simple list, an item to be searched is looked for in a sequential manner which gives the time complexity of O(n). But in real scenario not all the items are searched frequently and most of the time only few items are searched multiple times. So, a self organizing list uses this property (also known as locality of reference) that brings the most frequent used items at the head of the list. This increases the probability of finding the item at the start of the list and those elements which are rarely used are pushed to the back of the list. In Transpose Method, the node that is accessed is swapped with its predecessor. So if any node is accessed, it is swapped with the node in-front of it unless it is the first(head) node in the list. In simple terms the priority of an accessed node is increased slowly such that it eventually reaches the first position. The main difference between transpose method and other methods is that, it takes many accesses to bring a node to front. Examples:

Input :  list: 1, 2, 3, 4, 5, 6
searched: 4
Output : list: 1, 2, 4, 3, 5, 6

Input : list: 1, 2, 4, 3, 5, 6
searched: 5
Output : list: 1, 2, 4, 5, 3, 6

Explanation: In 1st case, 4 is swapped with its predecessor i.e. 3
In 2nd case, 5 is swapped with its predecessor i.e. again 3

C++




// CPP Program to implement self-organizing list
// using move to front method
#include <iostream>
using namespace std;
 
// structure for self organizing list
struct self_list {
    int value;
    struct self_list* next;
};
 
// head and rear pointing to start and end of list resp.
self_list *head = NULL, *rear = NULL;
 
// function to insert an element
void insert_self_list(int number)
{
    // creating a node
    self_list* temp = (self_list*)malloc(sizeof(self_list));
 
    // assigning value to the created node;
    temp->value = number;
    temp->next = NULL;
 
    // first element of list
    if (head == NULL)
        head = rear = temp;
 
    // rest elements of list
    else {
        rear->next = temp;
        rear = temp;
    }
}
 
// function to search the key in list
// and re-arrange self-organizing list
bool search_self_list(int key)
{
    // pointer to current node
    self_list* current = head;
 
    // pointer to previous node
    self_list* prev = NULL;
 
    // pointer to previous of previous
    self_list* prev_prev = NULL;
 
    // searching for the key
    while (current != NULL) {
 
        // if key found
        if (current->value == key) {
 
            // if key is neither the first element
            // and nor the second element
            if (prev_prev != NULL) {
 
                /* re-arranging the elements */
                prev_prev->next = current;
                prev->next = current->next;
                current->next = prev;
            }
 
            // if key is second element
            else if (prev != NULL) {
 
                /* re-arranging the elements */
                prev->next = current->next;
                current->next = prev;
                head = current;
            }
            return true;
        }
        prev_prev = prev;
        prev = current;
        current = current->next;
    }
 
    // key not found
    return false;
}
 
// function to display the list
void display()
{
    if (head == NULL) {
        cout << "List is empty" << endl;
        return;
    }
 
    // temporary pointer pointing to head
    self_list* temp = head;
    cout << "List: ";
 
    // sequentially displaying nodes
    while (temp != NULL) {
        cout << temp->value;
        if (temp->next != NULL)
            cout << " --> ";
 
        // incrementing node pointer.
        temp = temp->next;
    }
    cout << endl
         << endl;
}
 
// Driver Code
int main()
{
    /* inserting five values */
    insert_self_list(1);
    insert_self_list(2);
    insert_self_list(3);
    insert_self_list(4);
    insert_self_list(5);
    insert_self_list(6);
 
    // Display the list
    display();
 
    // search 4 and if found then re-arrange
    if (search_self_list(4))
        cout << "Searched: 4" << endl;
    else
        cout << "Not Found: 4" << endl;
 
    // Display the list
    display();
 
    // search 2 and if found then re-arrange
    if (search_self_list(5))
        cout << "Searched: 5" << endl;
    else
        cout << "Not Found: 5" << endl;
    display();
 
    return 0;
}


Java




// Java program to implement self-organizing list
// using move to front method
import java.io.*;
import java.util.*;
 
// Class for self organizing list
class SelfOrganizingList
{
  int value;
  SelfOrganizingList next;
// Constructor to initialize the list
    SelfOrganizingList (int number)
  {
    value = number;
    next = null;
  }
}
 
// Main class
class Main
{
// Head and rear pointing to start and end of list resp.
  static SelfOrganizingList head = null, rear = null;
// Function to insert an element in the list
  static void insertSelfOrganizingList (int number)
  {
    // creating a node
    SelfOrganizingList temp = new SelfOrganizingList (number);
 
    // First element of list
    if (head == null)
      head = rear = temp;
 
    // Rest elements of list
    else
      {
    rear.next = temp;
    rear = temp;
      }
  }
 
// Function to search the key in list
// and re-arrange self-organizing list
  static boolean searchSelfOrganizingList (int key)
  {
    // pointer to current node
    SelfOrganizingList current = head;
 
    // pointer to previous node
    SelfOrganizingList prev = null;
 
    // pointer to previous of previous
    SelfOrganizingList prev_prev = null;
 
    // searching for the key
    while (current != null)
      {
 
    // if key found
    if (current.value == key)
      {
 
        // if key is neither the first element
        // and nor the second element
        if (prev_prev != null)
          {
 
        /* re-arranging the elements */
        prev_prev.next = current;
        prev.next = current.next;
        current.next = prev;
          }
 
        // if key is second element
        else if (prev != null)
          {
 
        /* re-arranging the elements */
        prev.next = current.next;
        current.next = prev;
        head = current;
          }
        return true;
      }
    prev_prev = prev;
    prev = current;
    current = current.next;
      }
 
    // key not found
    return false;
  }
 
// Function to display the list
  static void display ()
  {
    if (head == null)
      {
    System.out.println ("List is empty");
    return;
      }
 
    // Temporary pointer pointing to head
    SelfOrganizingList temp = head;
    System.out.print ("List: ");
 
    // Sequentially displaying nodes
    while (temp != null)
      {
    System.out.print (temp.value);
    if (temp.next != null)
      System.out.print (" --> ");
 
    // Incrementing node pointer
    temp = temp.next;
      }
    System.out.println ("\n");
  }
 
// Driver code
  public static void main (String[]args)
  {
    /* inserting six values */
    insertSelfOrganizingList (1);
    insertSelfOrganizingList (2);
    insertSelfOrganizingList (3);
    insertSelfOrganizingList (4);
    insertSelfOrganizingList (5);
    insertSelfOrganizingList (6);
 
    // Display the list
    display ();
 
    // search 4 and if found then re-arrange
    if (searchSelfOrganizingList (4))
      System.out.println ("Searched: 4");
    else
      System.out.println ("Not Found: 4");
 
    // Display the list
    display ();
 
    // search 5 and if found then re-arrange
    if (searchSelfOrganizingList (5))
      System.out.println ("Searched: 5");
    else
      System.out.println ("Not Found: 5");
    display ();
  }
}


Python3




# Python3 Program to implement self-organizing list
# using move to front method
 
# self organize list class
 
 
class self_organize_list(object):
    # default constructor
    def __init__(self):
        self.__list = list()
        self.__size = 0
 
    # constructor to initialize list
    def __init__(self, lst):
        self.__list = lst
        self.__size = len(lst)
 
    # method to display the list
    def display(self):
        print("List: ", end='')
        for i in range(self.__size):
            if i != self.__size-1:
                print(self.__list[i], end=' --> ')
            else:
                print(self.__list[i])
        print()
 
    # method to search key in list
    def search(self, key):
        print("Searched: %d" % key)
        if key in self.__list:
                # finding the index of the key
            index = self.__list.index(key)
            if index != 0:
                # Moving the key forward in the list
                bkp = self.__list[index]
                self.__list.pop(index)
                self.__list.insert(index-1, bkp)
            return True
        return False
 
    # method to insert key in self organize list
    def insert(self, key):
        self.__list.append(key)
        self.__size = self.__size + 1
 
 
if __name__ == "__main__":
    # initial list of four elements
    lst = [1, 2, 3, 4, 5, 6]
    sol = self_organize_list(lst)
    sol.display()
 
    # inserting new element and display
    sol.search(4)
    sol.display()
 
    # sequence of search and display
    sol.search(5)
    sol.display()


C#




using System;
using System.Collections.Generic;
 
// SelfOrganizeList class
class SelfOrganizeList
{
    private List<int> _list;
    private int _size;
 
    // Default constructor
    public SelfOrganizeList()
    {
        _list = new List<int>();
        _size = 0;
    }
 
    // Constructor to initialize the list
    public SelfOrganizeList(List<int> lst)
    {
        _list = new List<int>(lst);
        _size = lst.Count;
    }
 
    // Method to display the list
    public void Display()
    {
        Console.Write("List: ");
        for (int i = 0; i < _size; i++)
        {
            if (i != _size - 1)
            {
                Console.Write(_list[i] + " --> ");
            }
            else
            {
                Console.WriteLine(_list[i]);
            }
        }
        Console.WriteLine();
    }
 
    // Method to search for a key in the list
    public bool Search(int key)
    {
        Console.WriteLine("Searched: {0}", key);
        if (_list.Contains(key))
        {
            // Finding the index of the key
            int index = _list.IndexOf(key);
            if (index != 0)
            {
                // Moving the key forward in the list
                int backup = _list[index];
                _list.RemoveAt(index);
                _list.Insert(index - 1, backup);
            }
            return true;
        }
        return false;
    }
 
    // Method to insert a key into the self-organize list
    public void Insert(int key)
    {
        _list.Add(key);
        _size = _list.Count;
    }
}
 
// Main class
class Program
{
    static void Main()
    {
        // Initial list of four elements
        List<int> lst = new List<int> { 1, 2, 3, 4, 5, 6 };
        SelfOrganizeList sol = new SelfOrganizeList(lst);
        sol.Display();
 
        // Inserting a new element and displaying
        sol.Search(4);
        sol.Display();
 
        // Sequence of search and display
        sol.Search(5);
        sol.Display();
    }
}


Output

List: 1 --> 2 --> 3 --> 4 --> 5 --> 6

Searched: 4
List: 1 --> 2 --> 4 --> 3 --> 5 --> 6

Searched: 5
List: 1 --> 2 --> 4 --> 5 --> 3 --> 6


Last Updated : 28 Dec, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads