链表系列-删除多余的元素LeetCode#83. Remove Duplicates from Sorted List

  • 题目:给定一个链表,删除链表里的重复元素(相同的元素只能在链表里出现一次)

  • 难度:Easy

  • 思路:对于链表操作的题目一般需要判头判空判尾,然后就是根据需要定义几个指针,对于此题只需要定义两个指针curr,next(一个指向当前元素,另一个根据是否和curr指针指向的值是重复元素来进行一定)

  • 代码:

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
public class Solution {
    public ListNode deleteDuplicates(ListNode head) {
        if(head == null || head.next == null){
            return head;
        }

        ListNode curr = head;
        ListNode next = curr.next;
        while(next != null){
            while(next != null && curr.val == next.val){
                next = next.next;
            }
            if(next == null){
                curr.next = null;
            }else if(curr.val != next.val){
                curr.next = next;
                curr = next;
                next = next.next;
            }
        }
        return head;
    }
}
  • 来自Discuss里的解题方法(利用递归来做)
public ListNode deleteDuplicates(ListNode head) {
        if(head == null || head.next == null)return head;
        head.next = deleteDuplicates(head.next);
        return head.val == head.next.val ? head.next : head;
}

LeetCode上大部分的链表操作算法题都能用递归实现

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值