(LeetCode 面试经典 150 题) 82. 删除排序链表中的重复元素 II (链表)

题目:82. 删除排序链表中的重复元素 II


思路:链表,时间复杂度0(n)。

C++版本:

cpp 复制代码
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    ListNode* deleteDuplicates(ListNode* head) {
    	//避免处理完后为空的情况
        ListNode new_head(0,head);
        ListNode *cur=&new_head;
        // 每次判断都判断两个连续相邻节点
        while(cur->next && cur->next->next){
            int val=cur->next->val;
            // 相等的话,说明这些相等的都不要
            if(cur->next->next->val==val){
            	// 进入循环,直到下一个节点不和val相等为止
                while(cur->next && cur->next->val==val){
                    cur->next=cur->next->next;
                }
            }else{
                cur=cur->next;
            }
        }
        return new_head.next;
    }
};

JAVA版本:

java 复制代码
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    public ListNode deleteDuplicates(ListNode head) {
        ListNode new_head=new ListNode(0,head);
        ListNode cur=new_head;
        while(cur.next!=null && cur.next.next!=null){
            int val=cur.next.val;
            if(cur.next.next.val==val){
                while(cur.next!=null && cur.next.val==val){
                    cur.next=cur.next.next;
                }
            }else{
                cur=cur.next;
            }
        }
        return new_head.next;
    }
}

GO版本:

go 复制代码
/**
 * Definition for singly-linked list.
 * type ListNode struct {
 *     Val int
 *     Next *ListNode
 * }
 */
func deleteDuplicates(head *ListNode) *ListNode {
    new_head:=&ListNode{Val:0,Next:head}
    cur:=new_head
    for cur.Next!=nil && cur.Next.Next!=nil {
        val:=cur.Next.Val
        if cur.Next.Next.Val==val {
            for cur.Next!=nil && cur.Next.Val==val {
                cur.Next=cur.Next.Next
            }
        }else{
            cur=cur.Next
        }
    }
    return new_head.Next
}
相关推荐
程序员爱钓鱼1 小时前
Go语言实战案例:简易JSON数据返回
后端·go·trae
程序员爱钓鱼1 小时前
Go语言实战案例:用net/http构建一个RESTful API
后端·go·trae
摇滚侠1 小时前
Oracle 关闭 impdp任务
java
快去睡觉~1 小时前
力扣238:除自身之外数组的乘积
数据结构·算法·leetcode
编程爱好者熊浪2 小时前
RedisBloom使用
java
苇柠2 小时前
Spring框架基础(1)
java·后端·spring
yics.2 小时前
数据结构——栈和队列
java·数据结构
在未来等你2 小时前
RabbitMQ面试精讲 Day 14:Federation插件与数据同步
中间件·面试·消息队列·rabbitmq
架构师沉默2 小时前
我用一个 Postgres 实现一整套后端架构!
java·spring boot·程序人生·架构·tdd
xiucai_cs2 小时前
布隆过滤器原理与Spring Boot实战
java·spring boot·后端·布隆过滤器