(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
}
相关推荐
NAGNIP3 小时前
万字长文!回归模型最全讲解!
算法·面试
之歆4 小时前
Spring AI入门到实战到原理源码-MCP
java·人工智能·spring
yangminlei4 小时前
Spring Boot3集成LiteFlow!轻松实现业务流程编排
java·spring boot·后端
qq_318121594 小时前
互联网大厂Java面试故事:从Spring Boot到微服务架构的技术挑战与解答
java·spring boot·redis·spring cloud·微服务·面试·内容社区
txinyu的博客4 小时前
解析业务层的key冲突问题
开发语言·c++·分布式
J_liaty4 小时前
Spring Boot整合Nacos:从入门到精通
java·spring boot·后端·nacos
阿蒙Amon5 小时前
C#每日面试题-Array和ArrayList的区别
java·开发语言·c#
daidaidaiyu5 小时前
Spring IOC 源码学习 一文学习完整的加载流程
java·spring
SmartRadio5 小时前
ESP32添加修改蓝牙名称和获取蓝牙连接状态的AT命令-完整UART BLE服务功能后的完整`main.c`代码
c语言·开发语言·c++·esp32·ble
2***d8855 小时前
SpringBoot 集成 Activiti 7 工作流引擎
java·spring boot·后端