列表

详情


剑指 Offer 24. 反转链表

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

 

示例:

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

 

限制:

0 <= 节点个数 <= 5000

 

注意:本题与主站 206 题相同:https://leetcode.cn/problems/reverse-linked-list/

原站题解

去查看

上次编辑到这里,代码来自缓存 点击恢复默认模板
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: ListNode* reverseList(ListNode* head) { } };

golang 解法, 执行用时: 0 ms, 内存消耗: 2.5 MB, 提交时间: 2021-05-28 11:47:48

/**
 * Definition for singly-linked list.
 * type ListNode struct {
 *     Val int
 *     Next *ListNode
 * }
 */
func reverseList(head *ListNode) *ListNode {
        cur := head
        var prev *ListNode
        var next *ListNode
        
        for cur != nil {
            next = cur.Next
            cur.Next = prev
            prev = cur
            cur = next
        }
        return prev
}

php 解法, 执行用时: 4 ms, 内存消耗: 16.8 MB, 提交时间: 2021-05-28 11:45:11

/**
 * Definition for a singly-linked list.
 * class ListNode {
 *     public $val = 0;
 *     public $next = null;
 *     function __construct($val) { $this->val = $val; }
 * }
 */
class Solution {

    /**
     * @param ListNode $head
     * @return ListNode
     */
    function reverseList($head) {
        $cur = $head;
        $next = null;
        $prev = null;
        while ( $cur != null ) {
            $next = $cur->next;
            $cur->next = $prev;
            // $cur->prev = $next;
            $prev = $cur;
            $cur = $next;
        }
        return $prev;
    }
}

上一题