我在开发链表类时难以模仿Java中的标准字符串和字符串构建器类。
我正在尝试学习如何使用和操作链接列表,我想创建一个名为LString
的类,它是一个由链接的字符列表而不是数组组成的字符串对象。
到目前为止,这是我理解设置Linked List类的方法:
public class LString {
//Fields
node front;
//node tail;?
int size;
// Node class
private class node {
char data;
node next;
//constructors
//default
public node (){
}
//data
public node (char newData){
this.data = newData;
}
//data + next
public node (char newData, node newNext){
this.data = newData;
this.next = newNext;
}
// Constructors
public LString(){
this.size = 0;
this.front = null;
}
//Methods
//append
public void append (char data){
this.size++;
if (front == null){
front = new node(data);
return;
}
node curr = front;
while (curr.next != null){
curr = curr.next;
}
curr.next = new node(data);
}
//prepend
public void prepend (int data){
front = new node(data, front);
size++;
}
//delete
public void delete(int index){
//assume that index is valid
if (index == 0){
front = front.next;
} else {
node curr = front;
for (int i = 0; i < index - 1; i++){
curr = curr.next;
}
curr.next = curr.next.next;
}
size--;
}
//toString
public String toString(){
StringBuilder result = new StringBuilder();
result.append('[');
node curr = front;
while (curr != null){
result.append(curr.data);
if (curr.next != null){
result.append(',');
}
curr = curr.next;
}
result.append(']');
return result.toString();
}
//add (at an index)
public void add(int index, int data){
if (index == 0){
front = new node(data, front);
} else {
node curr = front;
for (int i = 0; i < index - 1; i++){
curr = curr.next;
}
curr.next = new node(data, curr.next);
}
}
}
我收到此错误消息:
LString.java:41: error: invalid method declaration; return type required
public LString(){
通过添加以下内容,我已经看到了解决此问题的其他方法:
public static void main(String[] args) {
LString lstring = new LString();
}
但这对我不起作用。任何帮助表示赞赏。
答案 0 :(得分:2)
您需要关闭node
内部类的括号。在给定的代码中,public LString()
函数在node
类中定义,因此它应该具有返回类型。