zoukankan      html  css  js  c++  java
  • 剑指 Offer 24. 反转链表(简单)

    通过率 74.2%

    题目链接

    题目描述:

    定义一个函数,输入一个链表的头节点,反转该链表并输出反转后链表的头节点。

    示例:

    输入: 1->2->3->4->5->NULL
    输出: 5->4->3->2->1->NULL

    限制:

    0 <= 节点个数 <= 5000

    思路:

    反转链表,那么就改变箭头的方向(即next)

    用pre保存head的前一个节点,next保存head的后一个节点,然后改变head.next的指向为pre,再令head=next继续循环这些操作,直到head为null

     1 /*JavaScript*/
     2 /**
     3  * Definition for singly-linked list.
     4  * function ListNode(val) {
     5  *     this.val = val;
     6  *     this.next = null;
     7  * }
     8  */
     9 /**
    10  * @param {ListNode} head
    11  * @return {ListNode}
    12  */
    13 var reverseList = function(head) {
    14     var pre = null
    15     while(head) {
    16         var next = head.next
    17         head.next = pre
    18         pre = head
    19         head = next
    20     }
    21     return pre
    22 };
  • 相关阅读:
    macOS免费的NTFS读写软件
    Python模块和模块引用(一)
    Python Class (一)
    Ubuntu系统管理systemd
    Case Closed?
    The 'with' and 'as' Keywords
    Buffering Data
    rstrip
    堆排序
    堆 续9
  • 原文地址:https://www.cnblogs.com/wwqzbl/p/15121111.html
Copyright © 2011-2022 走看看