【面试题5】从尾到头打印链表

【题目描述】

输入一个链表的头结点,从尾到头反过来打印出每个结点的值。

【解决方案】

1. 最普通的方法,先反转链表,再输出。但是,由于反转会改变链表结构,不推荐;

2. 典型的“后进先出”,联想到栈,可以输出到栈中,再以此读取;

3. 栈可以用递归实现,故可以用递归实现。如果数据量大,可能导致方法调用栈溢出,所以,最好还是显示地用递归实现。

我的代码实现1,仅供参考:

 1         /// <summary>
 2         /// 反转链表后输出
 3         /// </summary>
 4         public static void PrintLinkedListValueReverse(ListNode head)
 5         {
 6             if (head == null)
 7                 return;
 8 
 9             ListNode headReverse = new ListNode(head.Value);
10             ListNode temp = null;
11 
12             //反转链表
13             while (head.Next != null)
14             {
15                 head = head.Next;
16                 temp = new ListNode(head.Value);
17                 temp.Next = headReverse;
18                 headReverse = temp;
19             }
20 
21             //输出反序链表
22             while (headReverse != null)
23             {
24                 Console.WriteLine(headReverse.Value);
25                 headReverse = headReverse.Next;
26             }
27         }

我的代码实现2,仅供参考:

 1         /// <summary>
 2         /// 利用栈输出
 3         /// </summary>
 4         public static void PrintLinkedListValueReverse(ListNode head)
 5         {
 6             if (head == null)
 7                 return;
 8 
 9             Stack<int> stack = new Stack<int>();
10 
11             //入栈
12             while (head != null)
13             {
14                 stack.Push(head.Value);
15                 head = head.Next;
16             }
17 
18             //出栈
19             while (stack.Count != 0)
20             {
21                 Console.WriteLine(stack.Pop());
22             }
23         }

我的代码实现3,仅供参考:

 1         /// <summary>
 2         /// 利用递归输出
 3         /// </summary>
 4         public static void PrintLinkedListValueReverse(ListNode head)
 5         {
 6             if (head != null)
 7             {
 8                 PrintLinkedListValueReverse(head.Next);
 9                 Console.WriteLine(head.Value);
10             }
11         }
原文地址:https://www.cnblogs.com/HuoAA/p/4797650.html