我是Java初学者,我目前正在开展一项我已经完成的项目。
我需要删除,修改和提取列表的元素(这是一个基本的元素,虽然我知道有arrayList(s)。)这让我发疯,因为我知道我需要做什么,但我我没有得到我需要开始编程的东西。
package lec05;
import java.util.*;
/**
*
* @author ulacit
*/
public class Lista {
Celda head;
public Lista() {
head = null;
}
public void add(Person aPerson) {
if (head == null) { // list = empty
head = new Celda(aPerson);
} else if (aPerson.getId() < head.getInfo().getId()) { // add element - left
Celda aux = new Celda(aPerson);
aux.setNext(head);
head = aux;
} else if (head.getNext() == null) { // add 1 element - right
Celda aux = new Celda(aPerson);
head.setNext(aux);
} else { // more than 1 - add at the end or in the middle
Celda actual = head;
while (actual.getNext() != null
&& actual.getNext().getInfo().getId() < aPerson.getId()) {
actual = actual.getNext();
}
Celda aux = new Celda(aPerson);
aux.setNext(actual.getNext());
actual.setNext(aux);
}
}
public boolean (int id) {
Celda aux = head;
while (aux != null && aux.getInfo().getId() < id) {
aux = aux.getNext();
}
return (aux != null && aux.getInfo().getId() == id);
}
public Person restore(int id) {
Celda aux = head;
while (aux != null && aux.getInfo().getId() < id) {
aux = aux.getNext();
}
if (aux != null && aux.getInfo().getId() == id) {
return aux.getInfo();
} else {
return null;
}
}
public void remove(int id) {
}
public void modify(int id, String name) {
}
public Persona extract(int id) {
}
@Override
public String toString() {
String s = "List{";
Celda aux = head;
while (aux != null) {
s += aux.getInfo() + ", ";
aux = aux.getNext();
}
return s;
}
}
答案 0 :(得分:1)
提示:
您不应该实现自己的列表数据结构......除非您特别要求执行此操作。最好使用现有的List
类型;例如ArrayList
或LinkedList
。
您的代码无法编译......
逐步开发:
在尝试编码其余方法之前,完成并测试add(Person)
,get(id)
和toString()
方法。
一次开发/测试其余方法。
实施您自己的单元测试。 (这不是强制性的,但它可以帮助您系统地测试代码。单元测试不需要漂亮......)
如果您遇到困难,有很多关于“数据结构和算法”的优秀教科书可以解释链表的工作原理。
您拥有的是单个链接列表;即,列表中的节点具有到下一个节点的链接......但不是前一个节点。在单个链表上执行操作的技巧是,当您迭代列表时,您(通常)需要跟踪保存链接到您“正在查看”的节点的节点。例如,要从列表中删除节点,您需要能够在当前节点之前修改节点。
答案 1 :(得分:1)
你可以做到这一点并不困难。
您拥有Lista
的头部,您拥有的是单个链接列表
以下是单个链表的说明。
所以当你打电话给例如remove(int x)
时,(假设x是Celda的id)
Some pseudocode
aux=Head
1. Check if you have aux (aux !=null)
2. Check if the aux has that id
2.1. if not move to the next Celda and start the same question (aux = aux.getNext())
2.2 if it has, you know what to delete, so you have to have a reference to the previous Celda of aux if it exist in this method, so know the previous.getNext() = aux.getNext()
如果您可以使用图像进行可视化,则可以更轻松地对其进行编码;)。
答案 2 :(得分:0)
如果要添加和删除,则需要指针。你继续引用“getNext”,但你没有下一个指针。将指针视为每个元素的连接。如果你有2个元素,你怎么知道哪个是第一个,哪个是第二个。你必须要有一些关系。
这是一个很棒的入门教程:http://www.dreamincode.net/forums/topic/143089-linked-list-tutorial/