输入一个连表的头结点,从尾到头反过来打印出每个结点的值。
C#语言实现:
public static void PrintRev(LinkedList<int> lList) { Stack<int> stack = new Stack<int>(); foreach (int item in lList) { stack.Push(item); } while (stack.Count > 0) { Console.WriteLine(stack.Pop()); } }
Java语言实现:
private static void printRev(LinkedList<Integer> lLink) { Stack<Integer> stack = new Stack<Integer>(); Iterator<Integer> it = lLink.iterator(); while(it.hasNext()){ stack.push(it.next()); } while (!stack.isEmpty()) { System.out.println(stack.pop()); } }
Python语言实现:
class Node(object): """ 单链表节点 """ def __init__(self, data=None, next=None): self.data = data self.next = next class LinkedList(object): def __init__(self, node=None): self.node = node def print_link_rev(self): """ 逆序打印链表 :return: """ lst = [] node = self.node while node: lst.append(node.data) node = node.next for data in sorted(lst, reverse=True): print(data)
本文出自 “许大树” 博客,请务必保留此出处http://abelxu.blog.51cto.com/9909959/1966050
原文地址:http://abelxu.blog.51cto.com/9909959/1966050