面试经典150题0530

面试经典150题0530

Leetcode082 删除排序链表中的重复元素

image-20240530160801327

当一个节点的后面两个节点都不为空时进行处理,先把后面第一个节点的值保存下来,然后对后面相邻的节点的值和当前保存的值进行比较,如果相邻的第二个节点和保存的值相同,处理的过程中应该从相邻的第一个节点开始。

public static ListNode deleteDuplicates(ListNode head) {
    ListNode dummy = new ListNode(101, head);
    ListNode curr = dummy;
    while (curr.next != null && curr.next.next != null){
        int val = curr.next.val;
        if(curr.next.next.val == val){
            while (curr.next != null && curr.next.val == val){
                curr.next = curr.next.next;
            }
        }
        else {
            curr = curr.next;
        }
    }
    return dummy.next;
}
Leetcode061 旋转链表
  • 如果为空链表直接返回null

  • 遍历链表获取链表的长度length

  • 通过传入的参数k对长度取模获取旋转的长度,使用length - k % length获取处理链表的位置。

image-20240530163609435

public static ListNode rotateRight(ListNode head, int k) {
    if(head == null){
        return null;
    }
    ListNode dummy = new ListNode(0, head);
    ListNode curr = dummy;
    int length = 0;
    while (curr.next != null){
        length++;
        curr = curr.next;
    }
    int pos = length - k % length;
    curr = dummy;
    while (pos-- > 0){
        curr = curr.next;
    }
    ListNode tmp = curr;
    while (curr.next != null){
        curr = curr.next;
    }
    curr.next = dummy.next;
    dummy.next = tmp.next;
    tmp.next = null;
    return dummy.next;
}
Leetcode086 分隔链表

image-20240530165422422

  • 新建两个头节点dummy1dummy2分别连接小于x和大于等于x的节点
  • 将小于x的链表的最后一个节点指向dummy2.next,将大于等于x的链表的最后一个节点指向null
public static ListNode partition(ListNode head, int x) {
    ListNode dummy1 = new ListNode();
    ListNode dummy2 = new ListNode();
    ListNode curr1 = dummy1, curr2 = dummy2;
    while (head != null){
        if(head.val < x){
            curr1.next = head;
            curr1 = curr1.next;
        }
        else {
            curr2.next = head;
            curr2 = curr2.next;
        }
        head = head.next;
    }
    curr2.next = null;
    curr1.next = dummy2.next;
    return dummy1.next;
}
Leetcode146 LRU缓存

https://blog.csdn.net/qq_43734400/article/details/138122492?spm=1001.2014.3001.5502

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值