单链表添加/删除

时间:2015-12-06 18:27:08

标签: java algorithm

我构建了一个像这样的单链表:

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

2 个答案:

答案 0 :(得分:1)

为什么不尝试以下

之类的内容
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;
 }

答案 1 :(得分:0)

我在稍微修改了@sreisman的代码后找到了答案。

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

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