当前位置:网站首页>[LeetCode] 83. Delete duplicate elements in the sorted list
[LeetCode] 83. Delete duplicate elements in the sorted list
2022-08-02 02:58:00 【Cake cake ~】
题目
给定一个已排序的链表的头 head , 删除所有重复的元素,使每个元素只出现一次 .返回 已排序的链表 .
示例 1:
输入:head = [1,1,2]
输出:[1,2]
示例 2:
输入:head = [1,1,2,3,3]
输出:[1,2,3]
提示:
链表中节点数目在范围 [0, 300] 内
-100 <= Node.val <= 100
题目数据保证链表已经按升序 排列
题解
双指针,a pointer to the first occurrence of the previous digit,One points to the first occurrence of the next digit
/** * 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* temp = head;
ListNode* temp1 = head;
while(temp != nullptr)
{
while(temp!= nullptr && temp->val == temp1->val)
{
temp = temp->next;
}
temp1->next = temp;
temp1 = temp1->next;
}
return head;
}
};
一次循环
/** * 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) {
if(head==nullptr || head->next==nullptr)
return head;
ListNode* temp = head;
while(temp->next)
{
if(temp->val == temp->next->val)
temp->next = temp->next->next;
else
temp = temp->next;
}
return head;
}
};
边栏推荐
猜你喜欢
随机推荐
极大似然估计
【Koltin Flow(三)】Flow操作符之中间操作符(一)
feign调用不通问题,JSON parse error Illegal character ((CTRL-CHAR, code 31)) only regular white space (r
aws s3 upload file
cadence landscape bindkey
PHP WebShell 免杀
Redis主从、哨兵、 Cluster集群一锅端!
2022牛客多校三_F G
【LeetCode】145.二叉树的后序遍历
IPFS部署及文件上传(golang)
网络层解析——IP协议、地址管理、路由选择
ApiFox 基本使用教程(浅尝辄止,非广)
canal同步Mariadb到Mysql
树链剖分-
数仓:数仓从ETL到ELT架构的转化以及俩者的区别
OC中成员变量,实例变量和属性之间的区别和联系
2W字!梳理50道经典计算机网络面试题(收藏版)
字符串常用方法
利用WebShell拿Shell技巧
Tree Chain Segmentation-









