代码编织梦想

83. Remove Duplicates from Sorted List

难度:easy
问题描述:
Given a sorted linked list, delete all duplicates such that each element appear only once.

中文:移除重复的节点
Example 1:

Input: 1->1->2
Output: 1->2

Example 2:

Input: 1->1->2->3->3
Output: 1->2->3

解法1:

简单暴力的遍历,注意判断空链表:

/**
 * 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) {}
 * };
 */
ListNode* deleteDuplicates(ListNode* head) {
        if(head == nullptr) return nullptr;
        ListNode* h = head;
        while(head->next != nullptr){
            if(head ->val != head->next->val){
                head = head->next;
            }else{
                head->next = head->next->next;
            }
        }
        return h;
    }

解法2:

递归法,判断前一个是否和后一个相等,如果相等则返回后一个。

ListNode* deleteDuplicates(ListNode* head) {
	if (!head || !head->next) return head;
		head->next = deleteDuplicates(head->next);
	return (head->val == head->next->val) ? head->next : head;
}

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。 本文链接: https://blog.csdn.net/makeyy123/article/details/111037960

leetcode学习笔记150 Evaluate Reverse Polish Notation-爱代码爱编程

leetcode学习笔记150 问题方法1 问题 Evaluate Reverse Polish Notation Evaluate the value of an arithmetic expression in Reverse Polish Notation. Valid operators are +, -, *, /. Each

leetcode69 x的平方根-爱代码爱编程

题目描述 题目链接 代码 public int mySqrt(int x) { int left = 0; int right = x; int res = -1; while (left <= right) { int mid = (left + righ

iOS LeetCode☞括号生成-爱代码爱编程

数字 n 代表生成括号的对数,请你设计一个函数,用于能够生成所有可能的并且 有效的 括号组合。 示例: 输入:n = 3 输出:[ "((()))", "(()())", "(())()", "()(())", "()()()" ] 题解: 为了生成所有序列,我们可以使

LeetCode——347. 前 K 个高频元素-爱代码爱编程

题目描述: 给定一个非空的整数数组,返回其中出现频率前 k 高的元素。 提示: 你可以假设给定的 k 总是合理的,且 1 ≤ k ≤ 数组中不相同的元素的个数。 你的算法的时间复杂度必须优于 O(n log n) , n 是数组的大小。 题目数据保证答案唯一,换句话说,数组中前 k 个高频元素的集合是唯一的。 你可以按任意顺序返回答案。 示例 1:

Day3-1 leetcode 283. Move Zeroes-爱代码爱编程

Given an array nums, write a function to move all 0’s to the end of it while maintaining the relative order of the non-zero elements. 方法一:直接遍历,一个个的把0往后面调整(但是有一个问题就是时间复杂度太高,leetc

22. 括号生成-爱代码爱编程

数字 n 代表生成括号的对数,请你设计一个函数,用于能够生成所有可能的并且 有效的 括号组合。 示例: 输入:n = 3 输出:[ “((()))”, “(()())”, “(())()”, “()(())”, “()()()” ] 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/generat