【发布时间】:2014-03-27 02:25:40
【问题描述】:
对于这个分配,我需要以链表作为参数,而不是节点,以递归方式反向打印链表。
我还必须使用我的教授提供的这个 SinglyLinkedList 类:
public class SinglyLinkedList<E> {
private int length; // # elements in the linked list
private SLNode<E> head; // access point to the linked list
private SLNode<E> tail;
public SinglyLinkedList() {
this.length = 0;
this.tail = new SLNode<E> (); // the tail dummy node
this.head = new SLNode<E> ( null, this.tail ); // the head dummy node
}
public int getLength() {
return this.length;
}
public void add( E e ) {
SLNode<E> newnode = new SLNode<E> ( e, null );
newnode.setSuccessor( this.head.getSuccessor() );
this.head.setSuccessor( newnode );
this.length++;
}
public void add( E e, int p ) {
// verify that index p is valid
if ( ( p < 0 ) || ( p > this.length ) ) {
throw new IndexOutOfBoundsException( "index " + p
+ " is out of range: 0 to " +
this.length );
}
SLNode<E> newnode = new SLNode<E> ( e, null );
SLNode<E> cursor = this.head;
for ( int i = 0; i < p; i++ ) {
cursor = cursor.getSuccessor();
}
addAfter( cursor, newnode );
this.length++;
}
public E remove( int p ) {
if ( ( p < 0 ) || ( p >= this.length ) ) {
throw new IndexOutOfBoundsException( "index " + p
+ " is out of range: 0 to " +
( this.length - 1 ) );
}
SLNode<E> cursor = head; // good for p == 0
if ( p > 0 ) {
cursor = find( p - 1 ); // get target's predecessor
}
SLNode<E> target = cursor.getSuccessor(); // get the node to remove
// link target to cursor's successor
cursor.setSuccessor( target.getSuccessor() );
target.setSuccessor( null );
cursor.setElement( null );
this.length--;
return target.getElement();
}
public E getElementAt( int p ) {
SLNode<E> node = this.find( p );
return node.getElement();
}
private void addAfter( SLNode<E> p, SLNode<E> newnode ) {
newnode.setSuccessor( p.getSuccessor() );
p.setSuccessor( newnode );
}
private SLNode<E> find( E target ) {
SLNode<E> cursor = head.getSuccessor();
while ( cursor != tail ) {
if ( cursor.getElement().equals( target ) ) {
return cursor; // success
}
else {
cursor = cursor.getSuccessor();
}
}
return null; // failure
}
private SLNode<E> find( int p ) {
if ( ( p < 0 ) || ( p >= this.length ) ) {
throw new IndexOutOfBoundsException();
}
SLNode<E> cursor = head.getSuccessor();
int i = 0;
while ( i != p ) {
cursor = cursor.getSuccessor();
i++;
}
return cursor;
}
}
我不知道如何通过传入对单链表而不是节点的引用来编写该方法。提前感谢您的帮助!
【问题讨论】:
-
想一想——如果您遍历列表并边走边打印,您将以“前进”顺序打印列表。如果您将列表走到最后,然后向后追溯您的步骤,在每个向后的步骤上打印,您将以“反向”顺序打印列表。您可以通过递归调用“遍历”列表,然后返回是“倒退”。
-
虽然我没有立即看到没有“遍历节点”的方法来做到这一点,而不是仅使用上述公共方法。似乎这样做的唯一方法是遍历列表(通过使用 elementAt 或在您行走时删除头节点)并在您行走时建立一个新列表,然后打印该新列表。
-
打印过程中可以修改(销毁)列表吗?还是应该保留?
-
我相信我可以在打印过程中修改列表。
-
@JustinBushy 不分析Hot Licks 刚才所说的,想想递归如何像堆栈一样(先调用后出)
标签: java