zoukankan      html  css  js  c++  java
  • 【IT笔试面试题整理】反转链表

    【试题描述】定义一个函数,输入一个链表的头节点,反转该链表并输出反转后链表的头节点

    【参考代码】

    方法一:

     1     public static Link reverseLinkList(Link head)
     2     {
     3         if (head == null || head.next == null)
     4             return head;
     5 
     6         Link pre = null;
     7         Link cur = head;
     8         Link back = head.next;
     9 
    10         while (back != null)
    11         {
    12             cur.next = pre;
    13             pre = cur;
    14             cur = back;
    15             back = back.next;
    16         }
    17         cur.next = pre; // 当current为最后一个节点时,back为null,所以要再指向前节点
    18         head = cur;
    19 
    20         return head;
    21     }

    方法二:

     1     public static Link reverseLinkList2(Link head)
     2     {
     3         if (head == null || head.next == null)
     4             return head;
     5         Link p1 = head;
     6         Link p2 = p1.next;// p2其实记录的下一步递归过程后的尾结点
     7         head = reverseLinkList2(p2);
     8         p2.next = p1;
     9         p1.next = null;
    10         return head;
    11     }
  • 相关阅读:
    Regexp:教程
    Regexp:目录
    笔记-C#:C# 方法、属性杂项-01
    Regexp:正则表达式应用——实例应用
    正则表达式:百科
    Regexp:template
    AngularJS:参考手册
    命令目录
    java实现连续数的公倍数
    java实现连续数的公倍数
  • 原文地址:https://www.cnblogs.com/WayneZeng/p/3015211.html
Copyright © 2011-2022 走看看