leetcode链表——203/206

一、203 移除链表元素

1.题目

https://leetcode-cn.com/problems/remove-linked-list-elements/
给你一个链表的头节点 head 和一个整数 val ,请你删除链表中所有满足 Node.val == val 的节点,并返回 新的头节点 。

2.原理

  1. 初始化一个节点,该节点的下一个指向链表的头结点
  2. 判断该节点的下一个阶段是否和val相同 相同就用指向next.next来删除节点,否则向下遍历
  3. 返回初始化的节点,因为可能有原链表被全部删除的情况 [7,7,7] 7

3.代码

class Solution {
    public ListNode removeElements(ListNode head, int val) {
        if(head == null) return head;
        ListNode newHead = new ListNode(0);
        newHead.next = head;
        ListNode cur = newHead;
        while(cur.next !=null){
            if (cur.next.val == val){
                cur.next = cur.next.next;
            }else{
                cur = cur.next;
            }
        }
        //return head;
        return newHead.next;

}
}

二、206. 反转链表

1.题目

https://leetcode-cn.com/problems/reverse-linked-list/

2.原理

  1. 三个指针,cur为当前指针,pre为cur的上一个指针,next为cur的下一个指针
  2. 先用next将cur.next节点保存起来,因为cur指向pre后,cur到next的联系就断了,不提前保存链表就断了,没办法继续往下走;
  3. cur指向pre
  4. cur赋值给pre,pre向前进
  5. next赋值给cur,cur向前进
  6. 最后cur指向尾节点的下一个,即null,所以要返回pre

3.代码

class Solution {
    public ListNode reverseList(ListNode head) {
        if(head == null || head.next == null) return head;
        ListNode cur =head;
        ListNode pre = null;
        ListNode next = null;
        while(cur!=null){
            next = cur.next;
            cur.next = pre;
            pre = cur;
            cur = next;
        }
        return pre;

    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值