题目:输入一个链表的节点,从头到尾反过来打印出每个节点的值
Java代码实现如下;
1.链表的创建
//定义链表
public class ListNode {
int val;
ListNode nextnode;
}
2、功能实现(方法一)
public class PrintListReverse {
public void PrintListReverse(ListNode headNode) {
Stack<ListNode> stack = new Stack<>();
while (headNode != null){
stack.push(headNode);//进栈
headNode = headNode.nextnode;
}
while (!stack.empty()){
ListNode popnode = stack.pop();//出栈(先进后出)
System.out.println(popnode.val);
}
}
}
功能实现方法二:
/**
* 输入一个链表的头结点,从头到尾反过来打印出每个节点的值
*
* 方法:该方法是以递归方式实现
*/
public class PrintListReverse1 {
public void PrintListReverse(ListNode headNode) {
if(headNode != null){
if (headNode.nextnode !=null){
PrintListReverse(headNode.nextnode);
}
}
System.out.println(headNode.val);
}
}
3、测试代码如下
public class Test {
public static void main(String[] args) {
ListNode node1 = new ListNode();
ListNode node2 = new ListNode();
ListNode node3 = new ListNode();
node1.val = 1;
node2.val = 2;
node3.val = 3;
node1.nextnode = node2;
node2.nextnode = node3;//以上是构建链表
PrintListReverse1 printListReverse = new PrintListReverse1();
printListReverse.PrintListReverse(node1);
}
}
测试结果如下;
3
2
1