题目:输入一个链表的头结点,从尾到头打印链表每个结点的值。
思路:从头到尾遍历链表,并用一个栈存储每个结点的值,之后出栈输出值即可。
Java版本:
import java.util.Stack;
public class Test {
public static class ListNode{
int value;//结点的值
ListNode nxt;//下一个节点
}
//采用栈的方式
public static void printListInverselyUsingIteration(ListNode root){
//创建一个栈
Stack<ListNode> stack = new Stack<>();
if(root == null){
System.out.println("链表为空");
}
while(root != null){
stack.push(root);
root = root.nxt;
}
ListNode tmp;
while(!stack.isEmpty()){
tmp = stack.pop();
System.out.print(tmp.value+" ");
}
}
public static void creatListNode(ListNode root1,int value,ListNode root2){
if(root1 == null){
System.out.println("链表为空");
}
root1.value = value;
root1.nxt = root2;
System.out.print(value + " ");
}
public static void main(String[] args) {
ListNode root1 = new ListNode();
ListNode root2 = new ListNode();
ListNode root3 = new ListNode();
ListNode root4 = new ListNode();
ListNode root5 = new ListNode();
ListNode root6 = new ListNode();
System.out.print("链表反转前:");
creatListNode(root1,12,root2);
creatListNode(root2, 4,root3);
creatListNode(root3,14,root4);
creatListNode(root4, 8,root5);
creatListNode(root5, 2,root6);
creatListNode(root6,30, null);
System.out.println();
System.out.print("链表反转后:");
printListInverselyUsingIteration(root1);
System.out.println();
printListInverselyUsingIteration(null);
}
}
Python版本:
# -*- coding: utf-8 -*-
class ListNode:
def __init__(self,x=None,next1=None):
self.value = x
self.next = next1
def creatListNode(node1,value,node2):
if node1 == None:
print('')
node1 = ListNode(value)
node1.next = node2
def printListFromTailToHead(ListNode):
if ListNode.value == None:
return
List=[]
head = ListNode
while head:
# 在第0个位置处插入结点,即最前面
List.insert(0,head.value)
head = head.next
print(List)
return 1
List=[15,11,7,18,2,4,11,6]
length = len(List)
Node =[]
for i in range(length):
Node.append(ListNode(List[i]))
for j in range(length):
if (j==length-1):
Node[j].next=None
else:
Node[j].next = Node[j+1]
print('链表反转前:')
print(List)
print('链表反转后:')
printListFromTailToHead(Node[0])