Tutorial de listas doblemente enlazadas

Una lista doblemente enlazada (DLL) contiene un puntero adicional, normalmente llamado puntero anterior, junto con el siguiente puntero y los datos que están allí en una lista enlazada individualmente. 
 

A continuación se muestran las operaciones en la DLL dada:
 

  1. Agregue un Node al frente de la DLL: el nuevo Node siempre se agrega antes del encabezado de la lista vinculada dada. Y el Node recién agregado se convierte en el nuevo jefe de DLL y mantiene una variable global para contar el número total de Nodes en ese momento.
     
  2. Recorrido de una lista doblemente enlazada
  3. Inserción de un Node: Esto se puede hacer de tres maneras: 
    • Al principio: el nuevo Node creado se inserta antes del Node principal y la cabeza apunta al nuevo Node.
    • Al final: el nuevo Node creado se inserta al final de la lista y la cola apunta al nuevo Node.
    • En una posición dada: Atraviese la DLL dada a esa posición ( deje que el Node sea X ) y luego haga lo siguiente: 
      1. Cambie el siguiente puntero del nuevo Node al siguiente puntero del Node X.
      2. Cambie el puntero anterior del siguiente Node del Node X al nuevo Node.
      3. Cambie el siguiente puntero del Node X al nuevo Node.
      4. Cambie el puntero anterior del nuevo Node al Node X.
  4. Eliminación de un Node: Esto se puede hacer de tres maneras: 
    • Al principio: mueva la cabeza al siguiente Node para eliminar el Node al principio y hacer que el puntero anterior de la cabeza actual sea NULL.
    • En el último: Mueva la cola al Node anterior para eliminar el Node al final y haga que el siguiente puntero del Node de cola sea NULL.
    • En una posición dada: Deje que el Node anterior del Node en la posición pos sea el Node X y el siguiente Node sea el Node Y, luego haga lo siguiente: 
      1. Cambie el siguiente puntero del Node X al Node Y.
      2. Cambie el puntero anterior del Node Y al Node X.

A continuación se muestra la implementación de todas las operaciones:
 

CPP

// C program to implement all functions
// used in Doubly Linked List
 
#include <stdio.h>
#include <stdlib.h>
int i = 0;
 
// Node for Doubly Linked List
typedef struct node {
    int key;
    struct node* prev;
    struct node* next;
 
} node;
 
// Head, Tail, first & temp Node
node* head = NULL;
node* first = NULL;
node* temp = NULL;
node* tail = NULL;
 
// Function to add a node in the
// Doubly Linked List
void addnode(int k)
{
 
    // Allocating memory
    // to the Node ptr
    node* ptr
        = (node*)malloc(sizeof(node));
 
    // Assign Key to value k
    ptr->key = k;
 
    // Next and prev pointer to NULL
    ptr->next = NULL;
    ptr->prev = NULL;
 
    // If Linked List is empty
    if (head == NULL) {
        head = ptr;
        first = head;
        tail = head;
    }
 
    // Else insert at the end of the
    // Linked List
    else {
        temp = ptr;
        first->next = temp;
        temp->prev = first;
        first = temp;
        tail = temp;
    }
 
    // Increment for number of Nodes
    // in the Doubly Linked List
    i++;
}
 
// Function to traverse the Doubly
// Linked List
void traverse()
{
    // Nodes points towards head node
    node* ptr = head;
 
    // While pointer is not NULL,
    // traverse and print the node
    while (ptr != NULL) {
 
        // Print key of the node
        printf("%d ", ptr->key);
        ptr = ptr->next;
    }
 
    printf("\n");
}
 
// Function to insert a node at the
// beginning of the linked list
void insertatbegin(int k)
{
 
    // Allocating memory
    // to the Node ptr
    node* ptr
        = (node*)malloc(sizeof(node));
 
    // Assign Key to value k
    ptr->key = k;
 
    // Next and prev pointer to NULL
    ptr->next = NULL;
    ptr->prev = NULL;
 
    // If head is NULL
    if (head == NULL) {
        first = ptr;
        first = head;
        tail = head;
    }
 
    // Else insert at beginning and
    // change the head to current node
    else {
        temp = ptr;
        temp->next = head;
        head->prev = temp;
        head = temp;
    }
    i++;
}
 
// Function to insert Node at end
void insertatend(int k)
{
 
    // Allocating memory
    // to the Node ptr
    node* ptr
        = (node*)malloc(sizeof(node));
 
    // Assign Key to value k
    ptr->key = k;
 
    // Next and prev pointer to NULL
    ptr->next = NULL;
    ptr->prev = NULL;
 
    // If head is NULL
    if (head == NULL) {
        first = ptr;
        first = head;
        tail = head;
    }
 
    // Else insert at the end
    else {
        temp = ptr;
        temp->prev = tail;
        tail->next = temp;
        tail = temp;
    }
    i++;
}
 
// Function to insert Node at any
// position pos
void insertatpos(int k, int pos)
{
 
    // For Invalid Position
    if (pos < 1 || pos > i + 1) {
        printf("Please enter a"
               " valid position\n");
    }
 
    // If position is at the front,
    // then call insertatbegin()
    else if (pos == 1) {
        insertatbegin(k);
    }
 
    // Position is at length of Linked
    // list + 1, then insert at the end
    else if (pos == i + 1) {
        insertatend(k);
    }
 
    // Else traverse till position pos
    // and insert the Node
    else {
        node* src = head;
 
        // Move head pointer to pos
        while (pos--) {
            src = src->next;
        }
 
        // Allocate memory to new Node
        node **da, **ba;
        node* ptr
            = (node*)malloc(
                sizeof(node));
        ptr->next = NULL;
        ptr->prev = NULL;
        ptr->key = k;
 
        // Change the previous and next
        // pointer of the nodes inserted
        // with previous and next node
        ba = &src;
        da = &(src->prev);
        ptr->next = (*ba);
        ptr->prev = (*da);
        (*da)->next = ptr;
        (*ba)->prev = ptr;
        i++;
    }
}
 
// Function to delete node at the
// beginning of the list
void delatbegin()
{
    // Move head to next and
    // decrease length by 1
    head = head->next;
    i--;
}
 
// Function to delete at the end
// of the list
void delatend()
{
    // Mode tail to the prev and
    // decrease length by 1
    tail = tail->prev;
    tail->next = NULL;
    i--;
}
 
// Function to delete the node at
// a given position pos
void delatpos(int pos)
{
 
    // If invalid position
    if (pos < 1 || pos > i + 1) {
        printf("Please enter a"
               " valid position\n");
    }
 
    // If position is 1, then
    // call delatbegin()
    else if (pos == 1) {
        delatbegin();
    }
 
    // If position is at the end, then
    // call delatend()
    else if (pos == i) {
        delatend();
    }
 
    // Else traverse till pos, and
    // delete the node at pos
    else {
        // Src node to find which
        // node to be deleted
        node* src = head;
        pos--;
 
        // Traverse node till pos
        while (pos--) {
            src = src->next;
        }
 
        // previous and after node
        // of the src node
        node **pre, **aft;
        pre = &(src->prev);
        aft = &(src->next);
 
        // Change the next and prev
        // pointer of pre and aft node
        (*pre)->next = (*aft);
        (*aft)->prev = (*pre);
 
        // Decrease the length of the
        // Linked List
        i--;
    }
}
 
// Driver Code
int main()
{
    // Adding node to the linked List
    addnode(2);
    addnode(4);
    addnode(9);
    addnode(1);
    addnode(21);
    addnode(22);
 
    // To print the linked List
    printf("Linked List: ");
    traverse();
 
    printf("\n");
 
    // To insert node at the beginning
    insertatbegin(1);
    printf("Linked List after"
           " inserting 1 "
           "at beginning: ");
    traverse();
 
    // To insert at the end
    insertatend(0);
    printf("Linked List after "
           "inserting 0 at end: ");
    traverse();
 
    // To insert Node with
    // value 44 after 3rd Node
    insertatpos(44, 3);
    printf("Linked List after "
           "inserting 44 "
           "after 3rd Node: ");
    traverse();
 
    printf("\n");
 
    // To delete node at the beginning
    delatbegin();
    printf("Linked List after "
           "deleting node "
           "at beginning: ");
    traverse();
 
    // To delete at the end
    delatend();
    printf("Linked List after "
           "deleting node at end: ");
    traverse();
 
    // To delete Node at position 5
    printf("Linked List after "
           "deleting node "
           "at position 5: ");
    delatpos(5);
    traverse();
 
    return 0;
}

Python3

# Python3 program to implement all functions
# used in Doubly Linked List
 
i = 0
 
# Node for Doubly Linked List
class node:
    def __init__(self, k=0, p=None, n=None):
        self.key = k
        self.prev = p
        self.next = n
 
 
# Head, Tail, first & temp Node
head = None
first = None
temp = None
tail = None
 
# Function to add a node in the
# Doubly Linked List
def addnode(k: int):
    global i, head, first, tail
    # Allocating memory
    # to the Node ptr
    ptr = node(k)
 
    # If Linked List is empty
    if head == None:
        head = ptr
        first = head
        tail = head
 
    # Else insert at the end of the
    # Linked List
    else:
        temp = ptr
        first.next = temp
        temp.prev = first
        first = temp
        tail = temp
 
    # Increment for number of Nodes
    # in the Doubly Linked List
    i += 1
 
 
# Function to traverse the Doubly
# Linked List
def traverse():
    # Nodes points towards head node
    ptr = head
 
    # While pointer is not None,
    # traverse and print the node
    while ptr != None:
 
        # Print key of the node
        print(ptr.key, end=" ")
        ptr = ptr.next
 
    print()
 
 
# Function to insert a node at the
# beginning of the linked list
def insertatbegin(k: int):
    global head, first, tail, i
 
    # Allocating memory
    # to the Node ptr
    ptr = node(k)
 
    # If head is None
    if head == None:
        first = ptr
        first = head
        tail = head
 
    # Else insert at beginning and
    # change the head to current node
    else:
        temp = ptr
        temp.next = head
        head.prev = temp
        head = temp
 
    i += 1
 
 
# Function to insert Node at end
def insertatend(k: int):
    global head, first, tail, i
 
    # Allocating memory
    # to the Node ptr
    ptr = node(k)
 
    # If head is None
    if head == None:
        first = ptr
        first = head
        tail = head
 
    # Else insert at the end
    else:
        temp = ptr
        temp.prev = tail
        tail.next = temp
        tail = temp
 
    i += 1
 
 
# Function to insert Node at any
# position pos
def insertatpos(k: int, pos: int):
    global i
 
    # For Invalid Position
    if pos < 1 or pos > i + 1:
        print("Please enter a" " valid position")
 
    # If position is at the front,
    # then call insertatbegin()
    elif pos == 1:
        insertatbegin(k)
 
    # Position is at length of Linked
    # list + 1, then insert at the end
    elif pos == i + 1:
        insertatend(k)
 
    # Else traverse till position pos
    # and insert the Node
    else:
        src = head
 
        # Move head pointer to pos
        while pos:
            pos -= 1
            src = src.next
 
        # Allocate memory to new Node
        ptr = node(k)
 
        # Change the previous and next
        # pointer of the nodes inserted
        # with previous and next node
        ptr.next = src
        ptr.prev = src.prev
        src.prev.next = ptr
        src.prev = ptr
        i += 1
 
 
# Function to delete node at the
# beginning of the list
def delatbegin():
    # Move head to next and
    # decrease length by 1
    global head, i
    head = head.next
    i -= 1
 
 
# Function to delete at the end
# of the list
def delatend():
    # Mode tail to the prev and
    # decrease length by 1
    global tail, i
    tail = tail.prev
    tail.next = None
    i -= 1
 
 
# Function to delete the node at
# a given position pos
def delatpos(pos: int):
    global i
    # If invalid position
    if pos < 1 or pos > i + 1:
        print("Please enter a" " valid position")
 
    # If position is 1, then
    # call delatbegin()
    elif pos == 1:
        delatbegin()
 
    # If position is at the end, then
    # call delatend()
    elif pos == i:
        delatend()
 
    # Else traverse till pos, and
    # delete the node at pos
    else:
        # Src node to find which
        # node to be deleted
        src = head
        pos -= 1
 
        # Traverse node till pos
        while pos:
            pos -= 1
            src = src.next
 
        # Change the next and prev
        # pointer of pre and aft node
        src.prev.next = src.next
        src.next.prev = src.prev
 
        # Decrease the length of the
        # Linked List
        i -= 1
 
 
# Driver Code
if __name__ == "__main__":
    # Adding node to the linked List
    addnode(2)
    addnode(4)
    addnode(9)
    addnode(1)
    addnode(21)
    addnode(22)
 
    # To print the linked List
    print("Linked List: ")
    traverse()
 
    print("\n")
 
    # To insert node at the beginning
    insertatbegin(1)
    print("Linked List after inserting 1 at beginning: ")
    traverse()
 
    # To insert at the end
    insertatend(0)
    print("Linked List after inserting 0 at end: ")
    traverse()
 
    # To insert Node with
    # value 44 after 3rd Node
    insertatpos(44, 3)
    print("Linked List after inserting 44 after 3rd Node: ")
    traverse()
 
    print("\n")
 
    # To delete node at the beginning
    delatbegin()
    print("Linked List after deleting node at beginning: ")
    traverse()
 
    # To delete at the end
    delatend()
    print("Linked List after deleting node at end: ")
    traverse()
 
    # To delete Node at position 5
    print("Linked List after deleting node at position 5: ")
    delatpos(5)
    traverse()
Salida: 
Lista enlazada: 2 4 9 1 21 22 
Lista enlazada después de insertar 1 al principio: 1 2 4 9 1 21 22 
Lista enlazada después de insertar 0 al final: 1 2 4 9 1 21 22 0 
Lista enlazada después de insertar 44 después del tercer Node : 1 2 4 44 9 1 21 22 0 
Lista enlazada después de eliminar el Node al principio: 2 4 44 9 1 21 22 0 
Lista enlazada después de eliminar el Node al final: 2 4 44 9 1 21 22 
Lista enlazada después de eliminar el Node en la posición 5: 2 4 44 9 21 22 
 

Publicación traducida automáticamente

Artículo escrito por siddharth_25 y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *