代码随想录Day03

01.移除链表元素

移除链表元素-leetcode

思路:设置虚拟头节点,采用前后节点的方式遍历链表。虚拟头节点为前一位,链表首位为当前节点。遍历过程中,如果当前节点的值等于val,就将前节点的next指向当前节点的next。

function removeElements(head: ListNode | null, val: number): ListNode | null {
    // 设置虚拟头节点
    const tmpNode:ListNode | null = new ListNode(0, head)
    // 前节点为虚拟头节点
    let prev:ListNode = tmpNode
    // 当前节点为链表首位
    let cur:ListNode = prev.next
    while (cur) {
        if (cur.val == val) {
            prev.next = cur.next
        } else {
            prev = cur
        }
        cur = cur.next
    }
    return tmpNode.next
};

02.设计链表

设计链表-leetcode

思路:创建一个私有方法getNode,用于获取第n位节点

class MyLinkedList {
    private length:number;
    private head:ListNode | null;
    private tail:ListNode | null;
    constructor() {
        this.length = 0;
        this.head = null;
        this.tail = null;
    }

    get(index: number): number {
        if (index < 0 || index >= this.length) {
            return -1
        }
        const cur = this.getNode(index);
        return cur.val
    }

    addAtHead(val: number): void {
        const first = new ListNode(val, this.head)
        this.head = first
        if (!this.tail) {
            this.tail = first
        }
        this.length++
    }

    addAtTail(val: number): void {
        const tail:ListNode = new ListNode(val)
        if (this.tail) {
            this.tail.next = tail
        } else {
            this.head = tail
        }
        this.tail = tail
        this.length++
    }

    addAtIndex(index: number, val: number): void {
        if (index > this.length) return 
        if (index == this.length) {
            this.addAtTail(val)
            return 
        } 
        if (index == 0) {
            this.addAtHead(val)
            return 
        } 
        const tmp = this.getNode(index - 1)
        const newNode = new ListNode(val, tmp.next)
        tmp.next = newNode;
        this.length++
    }

    deleteAtIndex(index: number): void {
        if (index >= this.length) return
        if (index == 0) {
            this.head = this.head!.next
            if (index === this.length - 1) {
                this.tail = null
            }
            this.length--
            return 
        }
        const cur = this.getNode(index - 1)
        cur.next = cur.next!.next
        if (index == this.length - 1) {
            this.tail = cur
        }
        this.length--
    }
    
    private getNode (index:number):ListNode {
        let cur:ListNode = new ListNode(0, this.head);
        for (let i = 0; i <= index; i++) {
            cur = cur.next!
        }
        return cur
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值