【题目描述】
给定一个已排序的链表的头 head , 删除所有重复的元素,使每个元素只出现一次 。返回 已排序的链表 。
【测试用例】
示例1:
输入:head = [1,1,2]
输出:[1,2]
示例2:
输入:head = [1,1,2,3,3]
输出:[1,2,3]
【思路分析】
这道题与简单篇第26题很类似,逻辑思路是一样的,只是26题是数组,本题是链表。可以参考26题的双指针做法,使用两个struct ListNode类型的指针一前一后指向链表中的元素,依次遍历,前后相等就让前指针直接指向后指针的next,前后不等就让前后指针均后移。
这里用单指针的做法,用一个struct ListNode类型的指针cur遍历整个链表,cur初始化指向head链表,判断cur->val与cur->next->val的关系:
如果 cur->val = cur->next->val,即两元素相等,让cur->next指向cur->next->next,即实现了删除一个相同的元素;
如果 cur->val != cur->next->val,即两元素不相等,直接让cur指针后移一位遍历下一个链表元素即可。
最后返回head链表。
注意:当head链表中没有元素和只有一个元素的时候,都可以直接返回head,用 if 语句做一个单独处理就可以了。
【参考代码】
C实现
#include <stdio.h>
#include <stdio.h>
//easy-83-删除排序链表中的重复元素
struct ListNode* deleteDuplicates(struct ListNode* head);
struct ListNode {
int val;
struct ListNode *next;
};
int main(){
struct ListNode *head, *tail;
head = NULL;
tail = head;
int arr[] = {1,1,2,3,3};
int len = sizeof(arr) / sizeof(arr[0]);
int i;
for(i=0;i<len;i++){
if(i==0){
head = (struct ListNode*)malloc(sizeof(struct ListNode));
tail = head;
tail->next = NULL;
tail->val = arr[i];
}else{
struct ListNode* cur = (struct ListNode*)malloc(sizeof(struct ListNode));
cur->next = NULL;
cur->val = arr[i];
tail->next = cur;
tail = cur;
}
}
struct ListNode* res = deleteDuplicates(head);
while(res != NULL){
printf("%d ", res->val);
res = res->next;
}
return 0;
}
struct ListNode* deleteDuplicates(struct ListNode* head) {
if(head == NULL || head->next == NULL){
return head;
}
struct ListNode* cur = head;
while(cur->next != NULL){
if(cur->val == cur->next->val){
cur->next = cur->next->next;
}else{
cur = cur->next;
}
}
return head;
}
C++实现
#include <iostream>
#include <vector>
using namespace std;
//easy-83-删除排序链表中的重复元素
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* Solution::deleteDuplicates(ListNode* head){
if(head == NULL || head->next == NULL){
return head;
}else {
struct ListNode* cur = head;
while(cur->next != NULL){
if(cur->val == cur->next->val){
cur->next = cur->next->next;
}else{
cur = cur->next;
}
}
}
return head;
}
int main(){
struct ListNode *head, *tail;
head = NULL;
tail = head;
vector<int> arr = {1,1,2,3,3};
int i;
for(i=0;i<arr.size();i++){
if(i == 0){
head = (struct ListNode*)malloc(sizeof(struct ListNode));
tail = head;
tail->val = arr[i];
tail->next = NULL;
}else{
struct ListNode* cur = (struct ListNode*)malloc(sizeof(struct ListNode));
cur->val = arr[i];
cur->next = NULL;
tail->next = cur;
tail = cur;
}
}
Solution sol;
struct ListNode *res;
res = sol.deleteDuplicates(head);
while(res != NULL){
cout<<res->val<<" ";
res = res->next;
}
return 0;
}

被折叠的 条评论
为什么被折叠?



