代码随想录算法训练营第3天 | 203.移除链表元素 707.设计链表 206.反转链表

51 阅读1分钟

203.移除链表元素

虚拟头结点法可以解决删除头结点的情况

/**
 * Definition for singly-linked list.
 * function ListNode(val, next) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.next = (next===undefined ? null : next)
 * }
 */
/**
 * @param {ListNode} head
 * @param {number} val
 * @return {ListNode}
 */
var removeElements = function(head, val) {
            // 虚拟头结点法
        const dummyHead = new ListNode(0, head);
        // 这里出错,需要仔细思考
        let cur = dummyHead;
        while (cur.next) {
            if (cur.next.val === val) {
                cur.next = cur.next.next;
            } else {
                cur = cur.next;
            }
        }
        return dummyHead.next;
};

707.设计链表

待更新

206.反转链表

1.双指针法

/**
 * Definition for singly-linked list.
 * function ListNode(val, next) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.next = (next===undefined ? null : next)
 * }
 */
/**
 * @param {ListNode} head
 * @return {ListNode}
 */
var reverseList = function(head) {
    // 双指针法
    let pre = null;
    let cur = head;
    let temp = null;
    while (cur) {
        temp = cur.next;
        cur.next = pre;
        pre = cur;
        cur = temp;
    }
    // 注意错误
    return pre;

};

2.递归法(待更新)