Imprimir sublista de una lista enlazada dada especificada por índices dados

Dada una Linkedlist y dos índices A y B , la tarea es imprimir una sublista comenzando desde A y terminando en B .

Ejemplos: 

Entrada: lista = 1 -> 2 -> 3 -> 4 -> 5 -> 6 -> 7 -> 8 -> 9 -> 10 -> NULO, A = 3, B = 9 
Salida: 3 4 5 6 7 8 9

Entrada: lista = 1 -> 3 -> 4 -> 10 -> NULO, A = 2, B = 2 
Salida:

Enfoque: 
siga los pasos a continuación para resolver el problema: 

  1. Cree tres variables de instancia: 
    1. actual: Encabezado de la lista enlazada dada
    2. subcurrent: cabeza de la sublista
    3. subend: Cola de la sublista.
  2. Recorra la lista vinculada e inicialice una variable index_count que se incrementa después de cada iteración.
  3. Establezca subcurrent como el Node al que se apunta actualmente cuando el valor de index_count es igual a A.
  4. Si index_count es igual a B, asigne un subextremo al Node actual al que se hace referencia. Señale subend.next a NULL para indicar el final de la sublista.
  5. Imprime el contenido de la lista de subcurrent a subend .

El siguiente código es la implementación del enfoque anterior: 

Java

// Java Program to find the
// subList in a linked list
 
import java.util.Scanner;
 
// Class representing the
// structure of a Linked List
public class LinkedListSublist {
    Node head;
    class Node {
        int data;
        Node next = null;
        Node(int new_data)
        {
            data = new_data;
        }
    }
 
    // Function to push node
    // at beginning of a
    // Linked List
    public void pushNode(int new_data)
    {
        Node new_node = new Node(new_data);
        new_node.next = head;
        head = new_node;
    }
 
    // Function to find sublist
    public Node subList(Node head,
                        int A,
                        int B)
    {
        Node subcurrent = null;
        Node subend = null;
        Node current = head;
        int i = 1;
 
        // traverse between indices
        while (current != null
               && i <= B) {
 
            // If the starting index
            // of the sublist is found
            if (i == A) {
                subcurrent = current;
            }
 
            // If the ending index of
            // the sublist is found
            if (i == B) {
                subend = current;
                subend.next = null;
            }
 
            // Move to next node
            current = current.next;
            i++;
        }
 
        // Return the head
        // of the sublist
        return subcurrent;
    }
 
    // Function to print
    // the linked list
    public void traversing()
    {
        Node current = head;
        while (current != null) {
            System.out.print(current.data
                             + " -> ");
            current = current.next;
        }
    }
 
    // Driver Program
    public static void main(String args[])
    {
 
        LinkedListSublist list
            = new LinkedListSublist();
        int N = 1;
        int value = 10;
 
        while (N < 11) {
            list.pushNode(value--);
            N++;
        }
 
        // Starting index
        int A = 3;
 
        // Ending index
        int B = 9;
 
        list.head
            = list.subList(
                list.head, A, B);
        list.traversing();
    }
}

Python3

# Python3 program to find the
# subList in a linked list
class Node:
     
    def __init__(self, data):
         
        self.data = data
        self.next = None
  
# Class representing the
# structure of a Linked List
class LinkedListSublist:
     
    def __init__(self):
         
        self.head = None
     
    # Function to push node
    # at beginning of a
    # Linked List
    def pushNode(self, new_data):
         
        new_node = Node(new_data)
        new_node.next = self.head
        self.head = new_node
     
    # Function to find sublist
    def subList(self, head, A, B):
         
        subcurrent = None
        subend = None
        current = self.head
        i = 1
  
        # Traverse between indices
        while (current != None and i <= B):
  
            # If the starting index
            # of the sublist is found
            if (i == A):
                subcurrent = current
  
            # If the ending index of
            # the sublist is found
            if (i == B):
                subend = current
                subend.next = None
  
            # Move to next node
            current = current.next
            i += 1
  
        # Return the head
        # of the sublist
        return subcurrent
         
    # Function to print
    # the linked list
    def traversing(self):
     
        current = self.head
         
        while (current != None):
            print(current.data, end = " -> ")
            current = current.next
  
# Driver Code
if __name__=='__main__':
     
    list = LinkedListSublist()
  
    N = 1
    value = 10
 
    while (N < 11):
        list.pushNode(value)
        value -= 1
        N += 1
 
    # Starting index
    A = 3
 
    # Ending index
    B = 9
 
    list.head = list.subList(list.head, A, B)
    list.traversing()
     
# This code is contributed by pratham76

C#

// C# Program to find the
// subList in a linked list
using System;
 
// Class representing the
// structure of a Linked List
public class LinkedListSublist
{
     
    public Node head;
    public class Node
    {
        public int data;
        public Node next = null;
        public Node(int new_data)
        {
            data = new_data;
        }
    }
  
    // Function to push node
    // at beginning of a
    // Linked List
    public void pushNode(int new_data)
    {
        Node new_node = new Node(new_data);
        new_node.next = head;
        head = new_node;
    }
  
    // Function to find sublist
    public Node subList(Node head,
                        int A,
                        int B)
    {
        Node subcurrent = null;
        Node subend = null;
        Node current = head;
        int i = 1;
  
        // traverse between indices
        while (current != null
               && i <= B)
        {
  
            // If the starting index
            // of the sublist is found
            if (i == A)
            {
                subcurrent = current;
            }
  
            // If the ending index of
            // the sublist is found
            if (i == B)
            {
                subend = current;
                subend.next = null;
            }
  
            // Move to next node
            current = current.next;
            i++;
        }
  
        // Return the head
        // of the sublist
        return subcurrent;
    }
  
    // Function to print
    // the linked list
    public void traversing()
    {
        Node current = head;
        while (current != null)
        {
            Console.Write(current.data
                             + " -> ");
            current = current.next;
        }
    }
  
    // Driver Program
    public static void Main(string []args)
    {
  
        LinkedListSublist list
            = new LinkedListSublist();
        int N = 1;
        int value = 10;
  
        while (N < 11)
        {
            list.pushNode(value--);
            N++;
        }
  
        // Starting index
        int A = 3;
  
        // Ending index
        int B = 9;
  
        list.head
            = list.subList(
                list.head, A, B);
        list.traversing();
    }
}
 
// This code is contributed by rutvik_56
Producción: 

3 -> 4 -> 5 -> 6 -> 7 -> 8 -> 9 ->

 

Complejidad temporal: O(N)  
Espacio auxiliar: O(1)
 

Publicación traducida automáticamente

Artículo escrito por VikasTomar 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 *