[英]java linked list copy constructor and constructor from string
我有2个关于链表的问题,所以我想我将它们发布在一个问题中。
首先,我将展示我的节点类以及复制构造函数和字符串构造函数
class CharNode
{
private char letter;
private CharNode next;
public CharNode(char ch, CharNode link)
{
letter = ch;
next = link;
}
public void setCharacter(char ch)
{
letter = ch;
}
public char getCharacter()
{
return letter;
}
public void setNext(CharNode next)
{
this.next = next;
}
public CharNode getNext()
{
return next;
}
}
复制构造函数
// copy constructor
public CharList(CharList l)
{
CharNode pt = head;
while(pt.getNext() != null)
{
this.setCharacter() = l.getCharacter();
this.setNext() = l.getNext();
}
}
字符串构造函数
// constructor from a String
public CharList(String s)
{
head = head.setCharacter(s);
}
当我尝试编译时,我的复制构造函数出现错误,它说它找不到符号this.setCharacter()
...和l.setCharacter()
...。
我只是做错了吗?
并从字符串我的构造函数,我知道那是错误的。 我考虑过使用charAt()
但是我怎么知道何时停止循环呢? 这是一个好方法吗?
任何帮助,将不胜感激。
在您的CharList构造函数中, this
引用CharList
类,该类没有setCharacter setCharacter()
方法(CharNode有)。 另外,在Java中调用方法时,需要传递参数,例如setFoo(newFoo)
,而不是setFoo() = newFoo
设置字符方法可能在您的节点中,而不在列表中。 您还需要移动指针。 我的意思是,您曾经在哪里“进入下一个节点”?
你的拷贝构造函数是类CharList
,而setCharacter
定义在CharNode
。
this
在拷贝构造函数引用构造函数中定义的CharList的当前实例对象。 l
也是CharList
在你的代码,而不是一个CharNode
定义setCharacter
。
复制构造函数应在CharNode
类中定义。
在您的“复制构造函数”中,您需要浏览从其头部开始传递的列表,并为新列表创建新节点...
public CharList(CharList l)
{
// Whatever method your CharList provides to get the
// first node in the list goes here
CharNode pt = l.head();
// create a new head node for *this* list
CharNode newNode = new CharNode();
this.head = newNode;
// Go through old list, copy data, create new nodes
// for this list.
while(pt != null)
{
newNode.setCharacter(pt.getCharacter());
pt = pt.getNext();
if (pt != null)
{
newNode.setNext(new CharNode());
newNode = newNode.getNext();
}
}
}
至于从String
创建列表...相同的概念,只是您遍历字符串而不是另一个CharList
for (int i = 0; i < myString.length(); i++)
{
...
newNode.setCharacter(myString.charAt(i));
...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.