【发布时间】:2020-03-08 11:26:36
【问题描述】:
我尝试使用下面的代码在java中实现一个链表:
class Linkedlist<T>{
private node head, tail;
public Linkedlist(){
head = new node(null);
tail = head;
}
public boolean insert(T value){
if(head.getValue() == null){
this.head.setValue(value);
head.setNext(null);
return true;
}
node insertNode = new node(value);
tail.setNext(insertNode);
tail = insertNode;
return true;
}
public boolean insert(T value, int index) {
if ( sizeOfList() == index + 1 ) return false;
node temp = this.head.getNext();
node prvtmp = this.head;
for (int i = 0; i <= index; i++) {
temp = temp.getNext();
prvtmp = temp;
System.out.println("for loop");
}
node insertNode = new node(value);
System.out.println("node created");
prvtmp.setNext(insertNode);
insertNode.setNext(temp);
System.out.println("temps");
return true;
}
public int sizeOfList(){
int size = 0;
node temp = this.head;
while(temp.getNext() != null){
temp = temp.getNext();
size++;
}
return size;
}
public String[] rtrnList(){
node temp = this.head;
int listSize = sizeOfList();
String[] resualt = new String[listSize + 1];
for (int i = 0;i <= listSize;i++){
resualt[i] = String.valueOf(temp.getValue());
temp = temp.getNext();
}
return resualt;
}
}
类节点:
public class node<T> {
private T value;
private node next;
public node(T value){
this.value = value;
this.next = null;
}
public void setValue(T value) {
this.value = value;
}
public void setNext(node next) {
this.next = next;
}
public T getValue() {
return value;
}
public node getNext() {
return next;
}
}
当我尝试使用一个参数运行 insert 方法时,它工作正常,但是当我使用两个参数运行它时:
import java.util.Arrays;
public class main {
public static void main(String[] args){
Linkedlist list = new Linkedlist();
list.insert(2);
list.insert(2);
list.insert(2);
list.insert(2);
list.insert(2);
list.insert(2);
list.insert(11, 3);
System.out.println(Arrays.toString(list.rtrnList()));
System.out.println("finished");
}
}
程序没有到达打印完成的行,但是如果我们删除该行:list.insert(11, 3);
然后程序就可以正常工作了。
输出:
for loop
for loop
for loop
for loop
node created
finish insert
【问题讨论】:
-
您的插入方法,如声明的那样,仅接受单个参数,如果您想处理多个参数,则需要其他重写此方法,或使用处理多个参数的不同签名重载它。
-
我重载插入方法我实际上有 2 个插入。
-
如果您还可以发布程序的输出,那将会很有帮助。你有很多
System.out.println()可以帮助追踪错误。 -
好的,我会编辑帖子
标签: java data-structures singly-linked-list