题目描述
输入个链表的头结点,从尾到头反过来打印出每个结点的值
java版
public static class ListNode {
int val; //节点的值
ListNode next; //下一个节点的值
public ListNode() {
}
public ListNode(int val) {
this.val = val;
}
}
//使用栈
public static void printListInverselyUsingStack(ListNode head) {
Stack<ListNode> stack = new Stack<>();
//入栈
while (head != null) {
stack.push(head);
head = head.next;
}
//出栈
ListNode temp;
while (!stack.empty()) {
temp = stack.pop();
System.out.println(temp.val+" ");
}
}
//使用递归
public static void printListInverselyUsingIteration(ListNode head){
if (head != null){
printListInverselyUsingStack(head.next);
System.out.println(111);
System.out.println(head.val);
}
}
public static void main(String[] args) {
ListNode root = new ListNode();
root.val=1;
root.next = new ListNode(2);
root.next.next = new ListNode(3);
root.next.next.next = new ListNode(4);
root.next.next.next.next = new ListNode(5);
// printListInverselyUsingStack(root);
// printListInverselyUsingStack(null);
printListInverselyUsingIteration(root);
}
python版
class ListNode:
def __init__(self,x=None):
self.val = x;
self.next = None
class solution:
def printListInverse(self,listNode):
if listNode == None:
return
temp = []
head = listNode
while head:
temp.insert(0, head.val)
head = head.next
return temp
node1=ListNode(10)
node2=ListNode(20)
node3=ListNode(30)
SimpleNode = ListNode(2)
test = ListNode()
node1.next = node2
node2.next = node3
s = solution()
print(s.printListInverse(node1))
print(s.printListInverse(test))
print(s.printListInverse(SimpleNode))