簡體   English   中英

單鏈列表添加/刪除

[英]singly linked list add/delete

我這樣構造了一個單鏈表:

public class LinkedList {

public LinkedList head;

String key;
LinkedList link;

public LinkedList(String key) {
    this.key = key;
    this.link = null;
    head = this;
}
public void headAdd(String key) {
    LinkedList temp = head;
    LinkedList newHead = new LinkedList(key);
    newHead.link = temp;
}

public void headDelete() {
head = head.link;
}

public String toString() {
    return key;
}

public static final String CANONICAL_NULL = "null list";
static final String NODE_LEFT = "(";
static final String NODE_RIGHT = ")";

public static String canonical(LinkedList list) {
    if (list == null) {
        return CANONICAL_NULL;
    }
    LinkedList current = list.head;
    StringBuffer sb = new StringBuffer();
    while (current != null) {
        sb.append(NODE_LEFT);
        sb.append(current.key);
        sb.append(NODE_RIGHT);
        current = current.link;
    }
    return sb.toString();
}
}

我想將headAdd()和headDelete()方法實現到此單鏈接列表。 使用此結構最簡單的方法是什么?

編輯: 測試用例

TEST:   linkedlist_headDelete_1 
description:    delete from 1-node list 
Correct:    ** null list ** 
Yours: ** null list ** 
5   SUCCESS 

TEST:   linkedlist_headDelete_2 
description:    delete from 2-node list 
Correct:    (b0) 
Yours: ** null list ** 
0   FAILED 

TEST:   linkedlist_headAdd_1 
description:    Add 1-node list 
Correct:    (b0) 
Yours: (b0) 
5   SUCCESS 

TEST:   linkedlist_headAdd_2 
description:    Add 2-node list 
Correct:    (b1)(b0) 
Yours: (b0) 
0   FAILED 

TEST:   linkedlist_headAdd_3 
description:    Add 3-node list 
Correct:    (b2)(b1)(b0) 
Yours: (b0) 
0   FAILED

您為什么不嘗試以下方法

public void headAdd(String key) {

     //hold old head node
     LinkedList temp = head;

     //create new head node
     LinkedList newHead = new LinkedList(key);
     while(newHead.hasNext())
     {
           newHead = newHead.link;
      }
     //Point new head node to old head node
     newHead.link = temp;

}

public void headDelete() {
     //Update head to be next link
     head = head.link;
}

boolean hasNext(LinkedList node)
{

      //check if node has another link
      if(node.link != null)
           return true;
      return false;
 }

在稍微更改@sreisman的代碼后,我找到了答案。

public void headAdd(String key) {
    LinkedList newHead = new LinkedList(key);
    newHead.link = head;
    head = newHead;
    }

public void headDelete() {
    head = head.link;
}

暫無
暫無

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

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