算法-链表

​​​​​​​

  • 移除链表元素
  • 反转链表

。。。补充中

第1题:移除链表元素 【核心:添加虚拟节点】

题意:删除链表中等于给定值 val 的所有节点。

图片

public class ListNode {
    public int val;
    public ListNode next;

    public ListNode(int val){
        this.val = val;
    }
}
public class Solution {
    public static void main(String[] args) {
        ListNode listNode = new ListNode(1);
        ListNode listNode1 = new ListNode(2);
        ListNode listNode2 = new ListNode(6);
        ListNode listNode3 = new ListNode(3);
        listNode.next=listNode1;
        listNode.next.next = listNode2;
        listNode.next.next.next=listNode3;

        ListNode listNode4 = new Solution().removeNode(listNode, 6);

        System.out.println(listNode4.next.next.val);
    }

    public ListNode removeNode(ListNode head, int n){
        ListNode header = new ListNode(-1);
        header.next = head;

        ListNode cur = header;
        while (cur.next != null){
            if (cur.next.val == n){
                cur.next = cur.next.next;
            }else {
                cur = cur.next;
            }
        }
        return header.next;
    }
}

206. 反转链表 【无敌双指针-需要前置节点+tmp节点】

给你单链表的头节点 head ,请你反转链表,并返回反转后的链表。

输入:head = [1,2,3,4,5]
输出:[5,4,3,2,1]

public ListNode reverseList(ListNode head){
        ListNode cur = null;
        ListNode pre = head;
        while (pre != null){
            ListNode tmp = pre.next;
            pre.next = cur;
            cur = pre;
            pre = tmp;
        }
        return cur;
    }

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值