题目:输入一个链表的头节点,从尾到头反过来打印出每个节点的值。
链表的定义:
/**
* 链表的实体类型
*/
public class ListNode {
int value; // 节点的值
ListNode listNode; // 类似于指针
public int getValue() {
return value;
}
public void setValue(int value) {
this.value = value;
}
public ListNode getListNode() {
return listNode;
}
public void setListNode(ListNode listNode) {
this.listNode = listNode;
}
}
具体的实现: 典型的‘后进先出’的栈操作类型;采用入栈出栈的方式进行输出处理
/**
* 从尾到头打印链表
*
* @param listNode 链表的头节点
*/
public void printListNode(ListNode listNode) {
// 初始化一个栈
Stack<ListNode> listNodeStack = new Stack<>();
while (listNode != null) {
// 将链表入栈
listNodeStack.push(listNode);
listNode = listNode.getListNode();
}
while (!listNodeStack.empty()) {
// 出栈并输出参数值
Log.i("chy===", "" + listNodeStack.pop().getValue());
}
}
________________________________________________________________________
/**
* 从尾到头打印链表---递归输出
*
* @param listNode 链表的头节点
*/
public void printListNode2(ListNode listNode) {
if (listNode != null) {
printListNode2(listNode.getListNode());
Log.i("chy1234","listNode===="+listNode.getValue());
}
}