我正在努力构建一个用于构建字符串的Linked List对象。我的班级LString
旨在模仿String
或StringBuilder
对象。它使用链表来形成字符串,而不是数组。我不确定如何形成构造函数。
到目前为止,这是我的代码:
public class LString {
// 2. Fields
node front;
//node tail;
int size;
// 1. Node class
private class node {
char data;
node next;
//constructors
//1. default
public node (){
}
//2. data
public node (char newData){
this.data = newData;
}
//3. data + next
public node (char newData, node newNext){
this.data = newData;
this.next = newNext;
}
}
// 3. Constructors
public LString(){
this.size = 0;
this.front = null;
}
public LString(String original) {
}
// 4. Methods
public int length() {
return this.size;
}
public int compareTo(LString anotherLString) {
return 0;
}
public boolean equals(Object other) {
if (other == null || !(other instanceof LString)) {
return false;
}
else {
LString otherLString = (LString)other;
return true;
}
}
public char charAt(int index) {
return 'a';
}
public void setCharAt(int index, char ch) {
ch = 'a';
}
public LString substring(int start, int end) {
return null;
}
public LString replace(int start, int end, LString lStr) {
return null;
}
//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 (char data){
/*node temp = new node(data);
temp.next = front;
front = temp;*/
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, char 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);
}
}
}
许多方法都是存根,因此该类将使用另一个测试文件进行编译。我不认为我需要包括它才能找到问题。
感谢您的帮助。
答案 0 :(得分:0)
您可以通过不同方式构建LString
构造函数。我能想到的一种方法是接受char[]
并将其存储在您的内部LinkedList中。您可以查看here中的String
个构造函数,以获得更多想法。