日期:2014-05-20  浏览次数:20722 次

怎么把一个单链表倒序输出
就是12345变成54321不能重建一个链表或者堆栈什么的。。。求代码
------最佳解决方案--------------------
public void turnList() throws Exception
{
if(head==null)
throw new Exception("null list");
else 
if(head==tail)
;
else
{
Node new_head=head;
while(head.next.next!=null)
{
Node temp=head.next;
head.next=temp.next;
temp.next=new_head;
new_head=temp;
}
tail.next=new_head;
Node temp=tail;
tail=head;
tail.next=null;
head=temp;
}
}
------其他解决方案--------------------
这种东西很无聊诶

不知道写这个有什么用,给你写一个吧。Java的


package link;
/**
 * 节点对象不用我写注释了吧
 * @author 
 * 创建时间:2011-4-1 上午10:15:18
 * 类说明:
 */
public class Node {

private int value = -1;

private Node next = null;

public Node(int value){
this.value = value;
}

public int getValue() {
return value;
}

public void setValue(int value) {
this.value = value;
}

public Node getNext() {
return next;
}

public void setNext(Node next) {
this.next = next;
}

@Override
public String toString() {
return "Node [value=" + value + "]";
}

}






package link;
/**
 * 链表类,注释我都加了
 * @author 
 * 创建时间:2011-4-1 上午10:16:46
 * 类说明:
 */
public class NodeList {

private Node head = null;

public Node getHead(){
return this.head;
}

/**
 * 对外公布的添加节点的方法
 * @param node
 */
public void addNode(Node node){
if(this.head == null){
/**
 * 如果头节点是空,就把要加的节点给头节点
 */
this.head = node;
}else{
/**
 * 否则把这个节点加到头节点后面的节点上
 */
this.addSubNode(this.head, node);
}
}

/**
 * 反向输出节点元素
 */
public void reversePrint(){
int size = this.getSize(0, this.head);

for(int index = size; index > 0; index--){
System.out.println(this.getNode(index));
}

}

/**
 * 给一个节点加子节点的方法
 * @param destNode
 * @param node
 */
private void addSubNode(Node destNode, Node node){
if(destNode.getNext() == null){
/**
 * 如果这个节点没有子节点则把新节点设置为这个节点的子节点
 */
destNode.setNext(node);
}else{
/**
 * 否则把新节点加到这个节点的子节点的后面
 */
this.addSubNode(destNode.getNext(), node);
}
}

/**
 * 得到下标对应的节点对象
 * @param index
 * @return
 */
private Node getNode(int index){

int start = 1;
Node currentNode = this.head;
while(start < index){