Link
上课:
class Link {
public String data1;
public Link nextLink;
//Link constructor
public Link() {
data1 = null;
}
public Link(String data) {
data1 = data;
}
public Link getNext() {
return nextLink;
}
public String getData() {
return data1;
}
//Print Link data
public String printLink() {
return "{" + data1 + "}";
}
}
SimpleLinkedList
上课:
class SimpleLinkedList {
private Link first;
//LinkList constructor
public SimpleLinkedList() {
first = null;
}
//Returns true if list is empty
public boolean isEmpty() {
return first == null;
}
//Inserts a new Link at the first of the list
public void add(String d1) {
Link link = new Link(d1);
link.nextLink = first;
first = link;
}
//Deletes the link at the first of the list
public String remove() {
Link temp = first;
first = first.nextLink;
return temp.toString();
}
public String get(int index) {
// post: returns the element at the specified position in this list.
// index must be 1 or higher
if (index <= 0)
return null;
Link current = first.getNext();
for (int i = 1; i < index; i++) {
if (current.getNext() == null)
return null;
current = current.getNext();
}
return current.getData();
}
//Prints list data
public String toString() {
Link currentLink = first;
String output = "";
System.out.print("List: ");
while (currentLink != null) {
output += currentLink.printLink();
currentLink = currentLink.nextLink;
}
return output;
}
}
这是我实施的链接列表。但是在remove方法中,我希望它从头部删除并返回被删除的字符串。无法做到这一点。
答案 0 :(得分:2)
您需要返回已移除的Link
:
public String remove() {
Link temp = first;
first = first.nextLink;
return temp.getData();
}