zoukankan      html  css  js  c++  java
  • 【面试题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         }
  • 相关阅读:
    iOS之上架打包时报错:ERROR ITMS-90086: "Missing 64-bit support.
    iOS之Xcode 8.0真机调试运行:This ** is running iOS 10.1.1 (14B100), which may not be supported
    The memory graph Shared by the method
    A memory map of an object
    Directly output the object name
    data encryption
    20181003-20181008
    Array inversion case
    No rabbit death problem
    Breakpoint debugging
  • 原文地址:https://www.cnblogs.com/HuoAA/p/4797650.html
Copyright © 2011-2022 走看看