[英]Creating own delete method in a doubly Linked List
我需要在雙鏈表中創建一個delete方法。 我遇到了麻煩,因為我認為我需要處理4個案件。
這是我到目前為止的代碼。
public void delete(Node n) {
if (head == null) {
System.out.println("the list is empty");
} else if (head != null) {
head = n;
Node newHead = n.next;
newHead = head;
} else if (n.next == null) {
Node beforeTail = n.previous;
beforeTail.next = null;
} else if (n.next != null || n.previous != null) {
Node inFront = n.previous;
Node inBack = n.next;
inFront.next = inBack;
inBack.previous = inFront;
} else {
System.out.println("error");
}
}
這是測試程序:
public class TestLL {
public static void main(String[] args){
/*Create a bunch of free standing nodes */
Node n1= new Node(new Integer(11));
Node n2= new Node(new Integer(12));
Node n3= new Node(new Integer(13));
Node n4= new Node(new Integer(14));
Node n5= new Node(new Integer(15));
Node n6= new Node(new Integer(16));
Node n7= new Node(new Integer(17));
/* link them */
LL myLL =new LL();
myLL.printList(); // prints "empty list"
myLL.add(n1); //11
myLL.add(n3); //13
myLL.add(n5); //15
myLL.add(n2); //12
myLL.add(n7); //17
myLL.printList(); //should print 11, 13, 15, 12, 17; one per line
System.out.println();
myLL.delete(n3);
myLL.addAfter(n4,n1);
myLL.printList(); //should print 11,14,15,12,17 one per line
System.out.println();
myLL.delete(n7);
myLL.delete(n2);
myLL.printList();//should print 11,14,15 one per line
}
}
我真的不確定該怎么做。 另外,我不能使用Java中已經存在的任何方法。
很難說,但是LL方法看起來是錯誤的。 通常,使用LL不需要“節點”的任何意識,因為這取決於實現處理所有鏈接詳細信息的實現。 調用的代碼應該傳遞給它選擇的對象。
我希望LL的使用看起來像這樣。
LL myLL = new LL();
myLL.add(new Integer(1));
myLL.add(new Integer(2));
// etc
myLL.remove(new Integer(1));
在添加新Node的調用過程中(LL的內部類)將被創建並附加到末尾。 刪除/刪除將搜索LL並刪除與傳入的對象匹配的第一個實例。
例如,LL實現的示意圖。
class LL
{
private Node headNode = null;
public void add(Object item)
{
// construct a new node
// iterate to the last node and add new node to the end
}
public boolean remove(Object item)
{
// starting at the head node search the list until a node with the matching item is found
// update the node pointers to "remove" the node
}
class Node
{
Node nextNode;
Node prevNode;
Object item;
}
}
我不會填寫實現,因為這是家庭作業;)但是您正確,有一些情況需要處理
祝好運!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.