当前位置:网站首页>[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;
}
};
边栏推荐
猜你喜欢
随机推荐
DVWA之SQL注入
240...循迹
C#测试项目中属性的用法
MySQL函数(经典收藏)
svm.SVC应用实践1--乳腺癌检测
【LeetCode】104.二叉树的最大深度
【LeetCode】145.二叉树的后序遍历
KICAD 拉线宽度无法修改,解决方法
Docker-compose安装mysql
Swift运行时(派发机制)
Flask之路由(app.route)详解
【LeetCode】94.二叉树的中序遍历
8万字带你入门Rust
AcWing 1285. Word Problem Solving (AC Automata)
VPS8701 电源管理(PMIC) VPS8701
PAT甲级打卡-1001-1004
analog IC layout-Parasitic effects
利用WebShell拿Shell技巧
Heuristic merge, DSU on Tree
EasyGBS平台播放视频时偶尔出现播放失败是什么原因?