JS刷题第三天|203.移除链表元素 、707.设计链表 、206.反转链表

链表理论基础

建议:了解一下链接基础,以及链表和数组的区别

文章链接:代码随想录

要会手写定义链表(JS)

class ListNode {
  val;
  next = null;
  constructor(value) {
    this.val = value;
    this.next = null;
  }
}

 203.移除链表元素

建议: 本题最关键是要理解 虚拟头结点的使用技巧,这个对链表题目很重要。

题目链接/文章讲解/视频讲解::代码随想录

题目容易理解,自己不熟悉链表相关代码,先看的视频思路,再尝试自己去写

单独处理头节点

var removeElements = function(head, val) {
    //移除头节点,将头结点向后移动一位就可以
while(head!=null&&head.val==val){
head=head.next
}
    //移除非头节点
    //定义一个指针指向head
    cur=head
    while(cur!=null&&cur.next!=null){
    if(cur.next.val==val){
  cur.next=cur.next.next
    } 
    else{
  cur=cur.next
    } 
    }
return head
};

用虚拟头节点来统一头节点和非头节点的删除方法

创建虚拟节点,定义临时指针来遍历链表

    //虚拟头节点,指向head
 const dummyhead = new ListNode(0, head);
 // 定义一个临时指针用来遍历列表
    let cur = dummyhead;
var removeElements = function(head, val) {
    //虚拟头节点
 const dummyhead = new ListNode(0, head);
 // 定义一个临时指针用来遍历列表
    let cur = dummyhead;
while(cur.next!=null){
    if(cur.next.val==val){
        cur.next=cur.next.next
    }else{
        cur=cur.next
    }
}
return dummyhead.next
};

707.设计链表

建议: 这是一道考察 链表综合操作的题目,不算容易,可以练一练 使用虚拟头结点

题目链接/文章讲解/视频讲解:代码随想录

只是看懂了,但是写不出来????

206.反转链表

建议先看我的视频讲解,视频讲解中对反转链表需要注意的点讲的很清晰了,看完之后大家的疑惑基本都解决了。

题目链接/文章讲解/视频讲解:代码随想录

 看到题目感觉思路不清晰,还是先看视频学习解题思路

双指针法:

注意处理空链表和只有头指针的情况

var reverseList = function(head) {
if(!head || !head.next) return head;
let temp = null, pre = null, cur = head;
while(cur)
{
    temp=cur.next
    cur.next=pre
    pre = cur;
    cur=temp
}
return pre
};

递归:和双指针方法一一对应,但是不如双指针法好理解

var reverse = function(cur, pre) {
    if(cur==null) return pre
    const temp = cur.next;
    cur.next = pre;
    return reverse(temp, cur);
}

var reverseList = function(head) {
    return reverse(head, null);
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值