简体   繁体   中英

Doubly Linked List Java

I'm having some confusion about creating my DLList in java. My instructions say that my DLLNode class should have links that point to the previous and next nodes. Do I need to create this under the data section or is it a method?

Thank you for your time

You can start declaring DDList like this:

public class DLList {
    private static class Node {
        int data;
        Node previous;
        Node next;
        Node(int d) { 
            data = d; 
        }
    }

    private Node head;
    private Node tail;
    // ...
 }

Some highlights:

  • The Node class is an inner class of DDList and thus a member. So it is declared in the same section as the other members, eg fields. This is what you call "data section" I believe.
  • You can declare head and tail before Node .
  • Thanks to static, Node does not have a reference to the DDList . This saves (only) 4 bytes per Node but can avoid memory leaks if you pass unlinked Nodes outside DDList . It is also better style ihmo.
  • Thanks to private, Node is not visible outside DLList . Since you need to access a class to access its fields, this is similar to setting Node 's fields as private. But it is more efficient because the compiler doesn't have to generate synthetic methods if you access Node 's fields in DLList .
  • Consider making data final, so it cannot change.
  • Consider making DDList generic. A cool exercise left to the reader :-)

This is a simple DLL Node class I've been using this for the past few semesters on multiple projects.

I warn you though, simply copying code can violate the honor code of your institution.

private class Node {
    public Node prev, next;
    int digit;

    // initializes the new node's values
    public Node(Node prev, int digit) {
        this.prev = prev;
        this.digit = digit;
        this.next = null;
    }
}

When you need to add a node, you just need to remember to link the previous nodes 'next' field to the new node.

Pretty much, you just need to create two references that refer to itself and called them next and previous. so for example:

private class Node {
   int data; // assuming the data is an integer
   Node next; // this is the next reference.
   Node previous; // this is the previous reference

   Node(int data) {
     this.data = data;
   }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM