簡體   English   中英

Java鏈表實現

[英]Java linked list implementation

我現在正在學習鏈表,我有點困惑。 我正在完成一項任務,我們正在創建我們自己的一些方法的實現,以與鏈表一起使用。

我看了很多關於鏈表概念的視頻,以及節點如何工作,比如獲取數據和設置下一個元素,但我對如何制作一個列表來測試我正在實現的方法感到困惑。 我知道這聽起來可能很愚蠢,但我開始對方法中的多個參數感到非常困惑,並且涉及到 return 語句,而且我之前從未使用過通用數據類型,所以這些基本想法可能會讓我感到困惑。

我希望在創建列表方面得到一些幫助,以便我可以在創建方法時對其進行測試,但我在打印列表時遇到了困難。 我知道我主要做的是創建新節點並添加到一些列表中,但老實說,我不知道這個所謂的 LinkedList 在哪里或它叫什么。 任何幫助是極大的贊賞!! 僅供參考,我對 Java 很陌生,這是我的第二堂課,它是在線的,而且不是一個結構很好的課程,請大聲笑

我明白了這個概念,但是這些被添加到的列表(或鏈接列表)的名稱是什么?

    ListNode node4 = new ListNode("Fourth", null);
    ListNode node3 = new ListNode("Third", node4);
    ListNode node2 = new ListNode("Second", node3);
    ListNode node1 = new ListNode("First", node2);

我不知道如何像上面那樣單獨打印這些內容,因為我可以使用上面的名稱

ListNode value = new ListNode("First", new ListNode("Second", new ListNode("Third", null) ));

這是我的測試類代碼,其中我有問題作為評論,如果我在上面沒有理解,這可能會幫助您理解我對什么感到困惑。 我省略了 ListNode 類,因為它是名為 ListNode 的基本 getNext() setNext() 節點類,具有通用類型......

//Testing program for SinglyLinkedList class
public class LinkedListDriver {

public static void main(String[] args) {
    //List<String> list = new LinkedList<String>();                   //comment out this line to test your code
    SinglyLinkedList<String> list = new SinglyLinkedList<String>();  //remove comment to test your code
    SinglyLinkedList SLL = new SinglyLinkedList();

    ListNode node4 = new ListNode("Fourth", null);
    ListNode node3 = new ListNode("Third", node4);
    ListNode node2 = new ListNode("Second", node3);
    ListNode node1 = new ListNode("First", node2);

//ListNode value = new ListNode("First", new ListNode("Second", new ListNode("Third", null) ));

System.out.println(node2.getData());

//Is this the correct way to add a new node to this method?
    SLL.addLast(new ListNode("Fifth", null));
//I doubt my printList is correct as I do not know what parameter I am       supposed to pass to it.    
    SLL.printList();
}

單鏈表類

//This class implements a very simple singly-linked list of Objects
public class SinglyLinkedList<E> {
     ListNode<E> first; // first element

public SinglyLinkedList()  {
    first = null;
}

public E getFirst() {
   if (first == null) {
      throw new NoSuchElementException();
   }
   else
      return first.getData();
   }

public void addFirst(E value) {
    first = new ListNode<E>(value, first);
}

// Methods below implemented by you. Note: while writing methods, keep in mind
// that you might be able to call other methods in this class to help you - you
// don't always need to start from scratch(but you'll have to recognize when)
public void addLast(E value) {    
    ListNode<E> temp = first;
    //If list is empty make new node the first node.
    if(temp == null) {
        first = new ListNode <E>(value, null);
        first.setNext(null);
    }
    //Otherwise loop to end of list and add new node.
    else {
        while(temp.getNext() != null) {
            temp = temp.getNext();
        }
    temp.setNext(new ListNode<E>(value, null));
    }
}//end addLast

// throws an exception - you decide when and which one
public E getLast() {
    ListNode<E> temp = first;
    if(temp == null) {
        throw new NullPointerException("There are no elements in this list to get.");
    }
    else {
        while(temp.getNext() != null) {
            temp = temp.getNext();
        }
        return temp.getData();
    }
}

// throws an exception - you decide when and which one
public E removeFirst() {
    if(first == null) {
        throw new NullPointerException("There are no elements in this list to remove.");
    }
    ListNode<E> tempRemove = first;  
    return null;//just so it'll compile
  }

  // throws an exception - you decide when and which one
  public E removeLast() {
     return null; //just so it'll compile
  }

  // return the number of elements in the list
  public int size() {
      return 0;//just so it'll compile
  }

  // return true if o is in this list, otherwise false
  public boolean contains(E obj) {
      return true;//just so it'll compile
  }

 public void printList(java.io.PrintStream out) {
     if(first == null) {
        System.out.println("The list is empty");
     }
     ListNode<E> current = first;
     while(current != null) {
         System.out.println(current.toString());
         current = current.getNext();
     }
  }

  public String toString() {
       String s = "[";
       ListNode<E> current = first;
    //write code to traverse the list, adding each object on its own line
    while(current.getNext() != null) {
        current = current.getNext();
    }

  s += "]";
  return s;
  }

  // OPTIONAL: just for fun...and a challenge
  public void reverse() {
  }
}    

鏈接列表是基本的數據結構。

基本的鏈表實現如下:

class LinkedListNode {
  int value;
  LinkedListNode next;
}

基本思想是,您可以通過檢查列表是否具有next參數來遍歷列表,如下所示: while (currentNode.next != null) { ... }

打印出鏈表的值將利用上述while循環,您只需打印當前節點的值即可。

您可以將鏈接列表視為僅能看到他們前面的人而看不到他們后面的人的一行。 您知道該行最開始的那個人(即沒有人在他身后的人)在哪里。 此人稱為列表的“頭”。 他知道誰在他前面,每個人都知道誰在他前面。 當您到達某人前面沒有任何人的地步時,您已經遍歷了整條線。

這是將新元素添加到列表末尾的示例:

LinkedListNode node = myListHead;
while (node.next != null) {
  node = node.next;
}
node.next = new LinkedListNode(...);

鏈接列表:

鏈表是一種線性數據結構,其中元素不存儲在連續的內存位置。 鏈表中的元素使用指針鏈接。

在 Java 中使用 class 實現鏈表:

在java中,我們可以將一個鏈表表示為一個類,將一個節點表示為一個單獨的類。 鏈表類將包含節點類類型的引用。

class LinkedList {
    Node head; // it is head of the list
    class Node {
        int data;
        Node next;
        Node(int d){data = d;}
    }
}

使用泛型在 Java 中實現鏈表:

與其他數據類型 String、Boolean、Float 和 Character 一樣,我們也可以實現一個通用的鏈表數據類型,它可以存儲任何數據類型的值。 讓我們看看單鏈表的實現。

    import java.io.*;
class node<T> {
    T data;
    node<T> next;
    node(T data)
    {

        this.data = data;
        this.next = null;

    }

}

class list<T> {

    node<T> head;

    private int length = 0;

    list() { this.head = null; }

    void add(T data)

    {

    node<T> temp = new node<>(data);

    if (this.head == null) {

            head = temp;

    }

 
else {
   node<T> X = head;
   while (X.next != null) {

       X = X.next;
   }
   X.next = temp;

 }
 length++;
}
void add(int position, T data)

    {
 if (position > length + 1) {
System.out.println(

                "Position Unavailable in LikedList");

            return;

        }
 if (position == 1) {
node<T> temp = head;
head = new node<T>(data);
head.next = temp;
return;

        }

node<T> temp = head;

   node<T> prev = new node<T>(null);

     while (position - 1 > 0) {

             prev = temp;

             temp = temp.next;

             position--;

        }

      prev.next = new node<T>(data);

        prev.next.next = temp;

    }

void remove(T key)

    {

  node<T> prev = new node<>(null);
prev.next = head;
node<T> next = head.next;
 node<T> temp = head;
  boolean exists = false;

 if (head.data == key) {

            head = head.next;
  exists = true;

        }
 while (temp.next != null) {

 if(String.valueOf(temp.data).equals(

                    String.valueOf(key))) {

prev.next = next;
 exists = true;
 break;

}
prev = temp;
temp = temp.next;
next = temp.next;
}
if(exists == false 
   && String.valueOf(temp.data).equals(
       String.valueOf(key)))
{
    prev.next = null;
    exists = true;
}
 if (exists) {
  length--;

        }

  else {

 System.out.println(

                "Given Value is not present in linked list");

        }

    }

void clear()

    {
 head = null;
  length = 0;

    }

boolean empty()

    {
  if (head == null) {
   return true;

        }

        return false;

    }

  int length() { return this.length; }

   public String toString()

    {

   String S = "{ ";

node<T> X = head;

  if (X == null)
  return S + " }";
while (X.next != null) {

  S += String.valueOf(X.data) + " -> ";

            X = X.next;

        }

 S += String.valueOf(X.data);

        return S + " }";

    }

}

 public class GFG {

public static void main(String[] args)

    {

  list<Integer> list1 = new list<>();

        System.out.println(

            "Integer LinkedList created as list1 :");

          list1.add(50);

          list1.add(150);

          list1.add(250);

System.out.println(

            "list1 after adding 50,150 and 250 :");

    System.out.println(list1);

  list1.remove(150);

  System.out.println("list1 after removing 150 :");

 System.out.println(list1);

  list<String> list2 = new list<>();

        System.out.println(

            "\nString LinkedList created as list2");
list2.add("welcome");
 list2.add("to");
list2.add("cse");
System.out.println(

            "list2 after adding welcome,to and cse :");

System.out.println(list2);

  list2.add(2, "GFG");

 System.out.println(

            "list2 after adding GFG at position 2 :");

 System.out.println(list2);
  list<Float> list3 = new list<>();
System.out.println(

            "\nFloat LinkedList created as list3");

 list3.add(21.10f);

  list3.add(55.30f);

  list3.add(40.80f);

 System.out.println(

            "list3 after adding 20.25, 50.42 and 30.99 :");

System.out.println(list3);

System.out.println("Clearing list3 :");

   list3.clear();

 System.out.println(list3);

}
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM