Open In App
Related Articles

Self Organizing List : Move to Front Method

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Report issue
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 Move to Front Method, the recently searched item is moved to the front of the list. So, this method is quite easy to implement but it also moves in-frequent searched items to front. This moving of in-frequent searched items to the front is a big disadvantage of this method because it affects the access time. 

 Examples:

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

Implementation:

CPP

// 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;
 
    // searching for the key
    while (current != NULL) {
 
        // if key found
        if (current->value == key) {
 
            // if key is not the first element
            if (prev != NULL) {
 
                /* re-arranging the elements */
                prev->next = current->next;
                current->next = head;
                head = current;
            }
            return true;
        }
        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);
 
    // 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(2))
        cout << "Searched: 2" << endl;
    else
        cout << "Not Found: 2" << endl;
    display();
 
    return 0;
}

                    

Java

// Java Program to implement self-organizing list
// using move to front method
 
public class SelfOrganizingList {
    // Structure for self-organizing list
    static class Node {
        int value;
        Node next;
    }
 
    // Head pointing to the start of the list
    static Node head = null;
 
    // Rear pointing to the end of the list
    static Node rear = null;
 
    // Function to insert an element
    static void insertSelfList(int number)
    {
        // Creating a node
        Node temp = new Node();
 
        // Assigning value to the created node
        temp.value = number;
        temp.next = null;
 
        // First element of the list
        if (head == null) {
            head = rear = temp;
        }
        else {
            // Rest of the elements in the list
            rear.next = temp;
            rear = temp;
        }
    }
 
    // Function to search for the key in the list
    // and re-arrange the self-organizing list
    static boolean searchSelfList(int key)
    {
        // Pointer to the current node
        Node current = head;
 
        // Pointer to the previous node
        Node prev = null;
 
        // Searching for the key
        while (current != null) {
            // If the key is found
            if (current.value == key) {
                // If the key is not the first element
                if (prev != null) {
                    // Re-arrange the elements
                    prev.next = current.next;
                    current.next = head;
                    head = current;
                }
                return true;
            }
            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 the head
        Node temp = head;
        System.out.print("List: ");
 
        // Sequentially display nodes
        while (temp != null) {
            System.out.print(temp.value);
            if (temp.next != null) {
                System.out.print(" --> ");
            }
 
            // Increment the node pointer
            temp = temp.next;
        }
        System.out.println("\n");
    }
 
    // Driver Code
    public static void main(String[] args)
    {
        // Inserting five values
        insertSelfList(1);
        insertSelfList(2);
        insertSelfList(3);
        insertSelfList(4);
        insertSelfList(5);
 
        // Display the list
        display();
 
        // Search for 4, and if found, then re-arrange
        if (searchSelfList(4)) {
            System.out.println("Searched: 4");
        }
        else {
            System.out.println("Not Found: 4");
        }
 
        // Display the list
        display();
 
        // Search for 2, and if found, then re-arrange
        if (searchSelfList(2)) {
            System.out.println("Searched: 2");
        }
        else {
            System.out.println("Not Found: 2");
        }
 
        display();
    }
}

                    

Python3

# Python program to implement self-organizing list
# using move to front method
 
# class for self-organizing list node
class self_list:
    def __init__(self, value=None, next=None):
        self.value = value
        self.next = next
 
# head and rear pointing to start and end of list resp.
head = None
rear = None
 
# function to insert an element
def insert_self_list(number):
    global head, rear
 
    # creating a node
    temp = self_list(number)
 
    # first element of list
    if head is None:
        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
def search_self_list(key):
    global head
 
    # pointer to current node
    current = head
 
    # pointer to previous node
    prev = None
 
    # searching for the key
    while current is not None:
 
        # if key found
        if current.value == key:
 
            # if key is not the first element
            if prev is not None:
 
                # re-arranging the elements
                prev.next = current.next
                current.next = head
                head = current
            return True
        prev = current
        current = current.next
 
    # key not found
    return False
 
# function to display the list
def display():
    global head
 
    if head is None:
        print("List is empty")
        return
 
    # temporary pointer pointing to head
    temp = head
    print("List: ", end="")
 
    # sequentially displaying nodes
    while temp is not None:
        print(temp.value, end="")
        if temp.next is not None:
            print(" --> ", end="")
 
        # incrementing node pointer.
        temp = temp.next
    print("\n")
 
# Driver Code
if __name__ == "__main__":
    # inserting five values
    insert_self_list(1)
    insert_self_list(2)
    insert_self_list(3)
    insert_self_list(4)
    insert_self_list(5)
 
    # Display the list
    display()
 
    # search 4 and if found then re-arrange
    if search_self_list(4):
        print("Searched: 4")
    else:
        print("Not Found: 4")
 
    # Display the list
    display()
 
    # search 2 and if found then re-arrange
    if search_self_list(2):
        print("Searched: 2")
    else:
        print("Not Found: 2")
    display()

                    

C#

using System;
 
public class SelfOrganizingList
{
    // Structure for self-organizing list
    public class Node
    {
        public int value;
        public Node next;
    }
 
    // Head pointing to the start of the list
    static Node head = null;
 
    // Rear pointing to the end of the list
    static Node rear = null;
 
    // Function to insert an element
    static void InsertSelfList(int number)
    {
        // Creating a node
        Node temp = new Node();
 
        // Assigning value to the created node
        temp.value = number;
        temp.next = null;
 
        // First element of the list
        if (head == null)
        {
            head = rear = temp;
        }
        else
        {
            // Rest of the elements in the list
            rear.next = temp;
            rear = temp;
        }
    }
 
    // Function to search for the key in the list
    // and re-arrange the self-organizing list
    static bool SearchSelfList(int key)
    {
        // Pointer to the current node
        Node current = head;
 
        // Pointer to the previous node
        Node prev = null;
 
        // Searching for the key
        while (current != null)
        {
            // If the key is found
            if (current.value == key)
            {
                // If the key is not the first element
                if (prev != null)
                {
                    // Re-arrange the elements
                    prev.next = current.next;
                    current.next = head;
                    head = current;
                }
                return true;
            }
            prev = current;
            current = current.next;
        }
 
        // Key not found
        return false;
    }
 
    // Function to display the list
    static void Display()
    {
        if (head == null)
        {
            Console.WriteLine("List is empty");
            return;
        }
 
        // Temporary pointer pointing to the head
        Node temp = head;
        Console.Write("List: ");
 
        // Sequentially display nodes
        while (temp != null)
        {
            Console.Write(temp.value);
            if (temp.next != null)
            {
                Console.Write(" --> ");
            }
 
            // Increment the node pointer
            temp = temp.next;
        }
        Console.WriteLine("\n");
    }
 
    // Driver Code
    public static void Main(string[] args)
    {
        // Inserting five values
        InsertSelfList(1);
        InsertSelfList(2);
        InsertSelfList(3);
        InsertSelfList(4);
        InsertSelfList(5);
 
        // Display the list
        Display();
 
        // Search for 4, and if found, then re-arrange
        if (SearchSelfList(4))
        {
            Console.WriteLine("Searched: 4");
        }
        else
        {
            Console.WriteLine("Not Found: 4");
        }
 
        // Display the list
        Display();
 
        // Search for 2, and if found, then re-arrange
        if (SearchSelfList(2))
        {
            Console.WriteLine("Searched: 2");
        }
        else
        {
            Console.WriteLine("Not Found: 2");
        }
 
        Display();
    }
}

                    

Javascript

// Node class for self-organizing list
class SelfListNode {
    constructor(value) {
        this.value = value;
        this.next = null;
    }
}
 
// Head and rear pointing to start and end of list respectively
let head = null;
let rear = null;
 
// Function to insert an element into the self-organizing list
function insertSelfList(number) {
    // Creating a new node
    const newNode = new SelfListNode(number);
 
    // First element of the list
    if (head === null) {
        head = rear = newNode;
    } else {
        rear.next = newNode;
        rear = newNode;
    }
}
 
// Function to search for a key in the self-organizing list
// and rearrange the list accordingly
function searchSelfList(key) {
    // Pointer to the current node
    let current = head;
 
    // Pointer to the previous node
    let prev = null;
 
    // Searching for the key
    while (current !== null) {
        // If key found
        if (current.value === key) {
            // If key is not the first element
            if (prev !== null) {
                // Rearranging the elements
                prev.next = current.next;
                current.next = head;
                head = current;
            }
            return true;
        }
        prev = current;
        current = current.next;
    }
 
    // Key not found
    return false;
}
 
// Function to display the self-organizing list
function display() {
    if (head === null) {
        console.log("List is empty");
        return;
    }
 
    // Temporary pointer pointing to the head
    let temp = head;
    let result = "List: ";
 
    // Sequentially displaying nodes
    while (temp !== null) {
        result += temp.value;
        if (temp.next !== null)
            result += " --> ";
 
        // Incrementing node pointer
        temp = temp.next;
    }
    console.log(result + "\n");
}
 
// Driver Code
(function main() {
    // Inserting five values
    insertSelfList(1);
    insertSelfList(2);
    insertSelfList(3);
    insertSelfList(4);
    insertSelfList(5);
 
    // Display the list
    display();
 
    // Search for 4 and rearrange if found
    if (searchSelfList(4))
        console.log("Searched: 4\n");
    else
        console.log("Not Found: 4\n");
 
    // Display the list
    display();
 
    // Search for 2 and rearrange if found
    if (searchSelfList(2))
        console.log("Searched: 2\n");
    else
        console.log("Not Found: 2\n");
 
    display();
})();

                    

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

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

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







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