[英]Linked List in Java method implementation
現在,我正在准備編寫代碼面試,我對Java中的鏈表有1個問題。 您能告訴我一些可靠的資源,從中我可以學習和實踐基本的鏈表方法。 我喜歡這個:www.cs.cmu.edu/~adamchik/15-121/lectures/Linked%20Lists/code/LinkedList.java,但是我對某些方法實現感到困惑。 例如,方法E get(int pos)返回NOT節點,但返回節點pos中包含的數據E。 而在這里http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/7u40-b43/java/util/LinkedList.java#LinkedList方法Node node(int index)返回節點在該位置(而不是其中包含的數據)。 我應該遵循哪種實施方式?
數據結構是一門非常概念化且基於上下文的學科。 每個數據結構存在的各種實現都是基於數據結構的要求和范圍。
甚至可以說Collection API
的LinkedList
實現是有問題的,因為如果多個線程同時工作,它就不能很好地工作。 然后, synchronizedList
從Collections
到制造類需要或至少需要使用與多線程效果很好的實現。
遵循使您LinkedList
的最低可行慣例,因為面試官不僅會問您LinkedList
實現。 面試官想知道的是您的概念和編碼技能是否達到一定水平。
想一想您可以使用Linked List
做什么。 為此,您必須考慮實際上要考慮的LinkedList
類型,因為存在許多不同類型的LinkedList
,例如SinglyLinkedList
, DoublyLinkedList
, SkipList
等。
考慮到SinglyLinkedList
,您的LinkedList
實現至少應具有以下方法: add()
, remove()
, contains()
, clear()
, size()
。
以下是我對SinglyLinkedList
實現:
import java.util.Iterator;
import java.util.StringJoiner;
public class LinkedList<T> implements Iterable<T>
{
private Node head;
private Node tail;
private int size;
private class Node
{
private T value;
private Node next;
public Node(T value)
{
this.value = value;
}
}
public void add(T value)
{
Node node = new Node(value);
if (head == null)
{
head = node;
}
else
{
tail.next = node;
}
tail = node;
++size;
}
public boolean remove(T value)
{
Node previous = null;
Node current = head;
while (head != null)
{
if (current.value.equals(value))
{
if (previous != null)
{
previous.next = current.next;
if (current.next == null)
{
tail = previous;
}
}
else
{
head = current.next;
if (head == null)
{
tail = null;
}
}
--size;
return true;
}
previous = current;
current = current.next;
}
return false;
}
public boolean contains(T value)
{
Node current = head;
while (current != null)
{
if (current.value.equals(value))
{
return true;
}
current = current.next;
}
return false;
}
public void clear()
{
head = null;
tail = null;
size = 0;
}
public int size()
{
return size;
}
@Override
public Iterator<T> iterator()
{
return new Iterator<T>()
{
private Node current = head;
@Override
public boolean hasNext()
{
return current != null;
}
@Override
public T next()
{
Node next = current;
current = current.next;
return next.value;
}
};
}
@Override
public String toString()
{
StringJoiner joiner = new StringJoiner(", ");
for (T value : this)
{
joiner.add(value.toString());
}
return joiner.toString();
}
}
如您所見,我的實現可能與其他地方的實現不同。 只要數據結構的概念沒有被根本改變並且只要它在其定義的接口下可以正常工作,就不會有微小的差異。
對於諸如數據結構之類的學科,您必須自己考慮並根據自己的需求,使用或實現適合您需求的數據結構。 就訪談而言,您需要展示的只是一個最低限度可行的數據結構的實現,而所有這些都是必需的。 只要確保這種最小可行的數據結構在上下文中沒有錯誤即可。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.