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         }
  • 相关阅读:
    Prim算法的3个版本
    [转]"undefined reference to" 问题解决方法
    C/C++ 读写 Excel
    Poj 3468
    关于PS中矩形工具的学习
    PS初学习
    java第二天学习。
    Java学习第一天
    二叉树的线索化
    struct files_struct
  • 原文地址:https://www.cnblogs.com/HuoAA/p/4833420.html
Copyright © 2011-2022 走看看