线性链表是一组节点。这是一个节点的定义方式(为了简单起见,我们不区分节点和列表):
class Node{
Object data;
Node link;
public Node(Object pData, Node pLink){
this.data = pData;
this.link = pLink;
}
public String toString(){
if(this.link != null){
return this.data.toString() + this.link.toString();
}else{
return this.data.toString() ;
}
}
public void inc(){
this.data = new Integer((Integer)this.data + 1);
}
public void lappend(Node list){
Node child = this.link;
while(child != null){
child = child.link;
}
child.link = list;
}
public Node copy(){
if(this.link != null){
return new Node(new Integer((Integer)this.data), this.link.copy());
}else{
return new Node(new Integer((Integer)this.data), null);
}
}
public Node invert(){
Node child = this.link;
while(child != null){
child = child.link;
}
child.link = this;....
}
}
我能够制作列表的深层副本。现在我想反转列表,以便第一个节点是最后一个,最后一个是第一个。倒排列表必须是深拷贝。
我开始开发反转功能,但我不确定。有任何想法吗?
更新:也许有一种递归方式,因为线性链表是一种递归数据结构。
我会取第一个元素,遍历列表,直到我到达一个没有子节点的节点并附加第一个元素,我会在第二个、第三个......