gpt4 book ai didi

java - 单向链表添加/删除

转载 作者:塔克拉玛干 更新时间:2023-11-03 06:20:53 25 4
gpt4 key购买 nike

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

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;
}

关于java - 单向链表添加/删除,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34121011/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com