当我跟踪lastC(链接列表中的最后一个节点)时,会出现问题。由于某种原因,在方法之外它似乎一直是空的。我想看看是否有更好的方法来跟踪它以改善我的程序的运行时间。
附加:
public MyStringBuilder append(String s)
{
if(this.length == 0) {
firstC = new CNode(s.charAt(0));
length = 1;
CNode currNode = firstC;
// Create remaining nodes, copying from String. Note
// how each new node is simply added to the end of the
// previous one. Trace this to see what is going on.
for (int i = 1; i < s.length(); i++)
{
CNode newNode = new CNode(s.charAt(i));
currNode.next = newNode;
currNode = newNode;
length++;
}
lastC = currNode;
//System.out.println(lastC.data);
//lastC.next = null;//new
} else {
if(lastC == null) {
lastC = getCNodeAt(length - 1);
//System.out.println("no");
}
//System.out.println(lastC.data);
//CNode currNode = lastC;
//CNode currNode = firstC;//changed
//for(int j = 0; j < length - 1; j++) {
// currNode = currNode.next;
//}
CNode currNode = lastC;
//lastC = currNode;
for (int i = 0; i < s.length(); i++)
{
CNode newNode = new CNode(s.charAt(i));
currNode.next = newNode;
currNode = newNode;//
length++;
}
lastC = currNode;
}
//lastC = getCNodeAt(length - 1);
return this;
}
构造函数:
public MyStringBuilder(String s)
{
if (s == null || s.length() == 0) // Special case for empty String
{ // or null reference
firstC = null;
lastC = null;
length = 0;
}
else
{
// Create front node to get started
firstC = new CNode(s.charAt(0));
length = 1;
CNode currNode = firstC;
// Create remaining nodes, copying from String. Note
// how each new node is simply added to the end of the
// previous one. Trace this to see what is going on.
for (int i = 1; i < s.length(); i++)
{
CNode newNode = new CNode(s.charAt(i));
currNode.next = newNode;
currNode = newNode;
length++;
}
lastC = currNode;
//lastC = getCNodeAt(length - 1);
//System.out.println(lastC.data);
}
}
实例变量
private CNode firstC; // reference to front of list. This reference is necessary
// to keep track of the list
private CNode lastC; // reference to last node of list. This reference is
// necessary to improve the efficiency of the append()
// method
private int length;
答案 0 :(得分:0)
建议:
sentinel
节点摆脱不必要的if
s append()
应为void
append()
,因为他们正在执行类似的工作不是Java程序员,但这样的事情应该有效:
public class MyStringBuilder {
private CNode sentinel = new CNode('s');
private CNode lastC = sentinel;
private int length = 0;
public MyStringBuilder(String s){
append(s);
}
public void append(String s){
for (int i = 1; i < s.length(); i++){
CNode newNode = new CNode(s.charAt(i));
lastC.next = newNode;
lastC = newNode;
length++;
}
}
public CNode getHead(){
return sentinel.next;
}
public CNode getTail(){
if (length) {
return lastC;
} else {
return null;
}
}
}