从尾到头打印链表(C#实现)

    xiaoxiao2025-04-02  2

    using System; using System.Collections.Generic; namespace 从尾到头打印链表 { class LinkNode { public int value; public LinkNode nextNode; public LinkNode(int value) { this.value = value; } } class Program { static void Main(string[] args) { InitData(); OppsiteDirectionPrintLinkNode(head); Console.ReadKey(); } public static LinkNode head = null; public static void InitData() { head = new LinkNode(0); LinkNode node2 = new LinkNode(3); head.nextNode = node2; LinkNode node3 = new LinkNode(5); node2.nextNode = node3; LinkNode node4 = new LinkNode(10); node3.nextNode = node4; } public static void OppsiteDirectionPrintLinkNode(LinkNode head) { Stack<int> valuesStack = new Stack<int>(); LinkNode temp = head; while (temp.nextNode != null) { valuesStack.Push(temp.value); temp = temp.nextNode; } valuesStack.Push(temp.value); int count = 0; int stackCount = valuesStack.Count; while (count < stackCount) { Console.WriteLine(valuesStack.Pop()); count++; } } } }

     

    最新回复(0)