Java >> Java tutorial >  >> Java

Find længden af ​​en linket listedatastruktur (iterativ og rekursiv)

Hvordan finder man længden af ​​linket listedatastruktur?

Linket liste

En sammenkædet liste er en lineær datastruktur, hvor hvert element er et separat objekt. At tælle en node i en linket liste er vigtig i programmering, når vi bruger en linket listedatastruktur. Det vil hjælpe dig med at løse mange problemer som f.eks. at finde n'te node fra sidst. Så gør god programmeringspraksis, det kan dit næste interviewspørgsmål.

Metode 1. Iterativ : Iterationen anvendes på det sæt instruktioner, som vi ønsker at få udført gentagne gange.

package in.eyehunt.data.struc;

// Linked list Node.
class Node {
    int data;
    Node next;
    // Parameterized constructor
    Node(int d) {
        data = d;
        next = null;
    }
}
public class LinkedList {

    Node head; // head of list
    //Returns count of nodes in linked list (iteration)
    public int count() {
        int a = 0;
        Node n = head;
        while (n != null) {
            n = n.next;
            a++;
        }
        return a;
    }
    public static void main(String a[]) {
        //create a simple linked list with 3 nodes
        LinkedList linkedList = new LinkedList();
        linkedList.head = new Node(2);
        Node second = new Node(4);
        Node third = new Node(5);
        linkedList.head.next = second;
        second.next = third;

        System.out.print("Total nodes in LikedList is : " + linkedList.count());
    }
}

Output :Samlet antal noder i LikedList er:3

Metode 2. Rekursiv : Rekursion er en proces, hvor udsagn i en funktionstekst kalder selve funktionen.

package in.eyehunt.data.struc;

// Linked list Node.
class Node {
    int data;
    Node next;
    // Parameterized constructor
    Node(int d) {
        data = d;
        next = null;
    }
}
public class LinkedList {

    Node head; // head of list

    //Returns count of nodes in linked list (Recursion)
    public int countRecursive(Node node) {
        if (node == null ){
            return 0;
        }
        return 1 + countRecursive(node.next);
    }
    public static void main(String a[]) {

        //create a simple linked list with 3 nodes
        LinkedList linkedList = new LinkedList();
        linkedList.head = new Node(2);
        Node second = new Node(4);
        Node third = new Node(5);
        Node fourth = new Node(9);
        linkedList.head.next = second;
        second.next = third;
        third.next = fourth;

        System.out.print("Total nodes in LikedList is : " + linkedList.countRecursive(linkedList.head));

    }
}

Output :Det samlede antal noder i LikedList er:4

Find længde på en linket liste datastruktur er relateret topspørgsmål i en liste over. Baseret på denne Find længde på linket liste kan du løse mange spørgsmål om linket liste.


Java tag