mengjian-github/leetcode

剑指 Offer 24. 反转链表

mengjian-github opened this issue · 2 comments

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

 

示例:

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

来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/fan-zhuan-lian-biao-lcof
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

思路1:创建一个新的链表返回:

/**
 * Definition for singly-linked list.
 * function ListNode(val) {
 *     this.val = val;
 *     this.next = null;
 * }
 */
/**
 * @param {ListNode} head
 * @return {ListNode}
 */
var reverseList = function(head) {
    let result = null;
    while(head) {
        const n = new ListNode(head.val);
        n.next = result;
        result = n;
        head = head.next;
    }
    return result;
};

思路2:可以不创建一个链表,直接遍历每个节点,改变next就好,不过要保存一下上一个节点:

/**
 * Definition for singly-linked list.
 * function ListNode(val) {
 *     this.val = val;
 *     this.next = null;
 * }
 */
/**
 * @param {ListNode} head
 * @return {ListNode}
 */
var reverseList = function(head) {
    let prev = null;
    let cur = null;
    while(head) {
        cur = head;
        head = head.next;
        cur.next = prev;
        prev = cur;
    }
    return prev;
};