zoukankan      html  css  js  c++  java
  • 反转单链表

    1. 非递归 - 无头结点

     1         /// <summary>
     2         /// 非递归 - 无头结点
     3         /// </summary>
     4         /// <param name="head"></param>
     5         public static ListNode ReverseList(ListNode head)
     6         {
     7             if (head == null)
     8                 return null;
     9 
    10             ListNode newHead = head;
    11             ListNode temp =null;
    12 
    13             head = head.Next;
    14             newHead.Next = null;
    15 
    16             while (head != null)
    17             {
    18                 temp = newHead;
    19                 newHead = head;
    20                 head = head.Next;
    21                 newHead.Next = temp;
    22             }
    23 
    24             return newHead;
    25         }

    2. 非递归 - 有头结点

     1         /// <summary>
     2         /// 非递归 - 有头结点
     3         /// </summary>
     4         /// <param name="head"></param>
     5         public static ListNode ReverseList(ListNode head)
     6         {
     7             if (head == null)
     8                 return null;            
     9 
    10             ListNode newHead = new ListNode(head.Value);
    11             ListNode temp =null;
    12 
    13             while (head.Next != null)
    14             {
    15                 temp = newHead.Next;
    16                 newHead.Next = head.Next;
    17                 head.Next = head.Next.Next;
    18                 newHead.Next.Next = temp;
    19             }
    20 
    21             return newHead;
    22         }

    3. 递归 - 无头结点

     1         /// <summary>
     2         /// 递归
     3         /// </summary>
     4         /// <param name="head"></param>
     5         public static ListNode ReverseList(ListNode head)
     6         {
     7             if (head == null || head.Next == null)
     8                 return head;
     9 
    10             ListNode newHead = ReverseList(head.Next);
    11 
    12             head.Next.Next = head;
    13             head.Next = null;
    14 
    15             return newHead;
    16         }
  • 相关阅读:
    用GitHub Pages搭建博客(三)
    Beta阶段项目总结
    最终团队绩效评估
    Alpha阶段项目总结
    项目发布
    Alpha版总结会议
    第二次冲刺周期站立会议(10)
    第二次冲刺周期站立会议(9)
    第二次冲刺周期站立会议(8)
    第二次冲刺周期站立会议(7)
  • 原文地址:https://www.cnblogs.com/HuoAA/p/4833420.html
Copyright © 2011-2022 走看看