Remove Duplicates from Sorted List Solutions in C++
Number 83
Difficulty Easy
Acceptance 45.5%
Link LeetCode
Other languages Go
Solutions
C++ solution by haoel/leetcode
// Source : https://oj.leetcode.com/problems/remove-duplicates-from-sorted-list/// Author : Hao Chen// Date : 2014-06-21#include <stdio.h>struct ListNode {int val;ListNode *next;ListNode(int x) : val(x), next(NULL) {}};ListNode *deleteDuplicates(ListNode *head) {for(ListNode *p=head; p && p->next; ){if (p->val == p->next->val){p->next = p->next->next;continue;}p=p->next;}return head;}void printList(ListNode* h){while(h!=NULL){printf("%d ", h->val);h = h->next;}printf("\n");}ListNode* createList(int a[], int n){ListNode *head=NULL, *p=NULL;for(int i=0; i<n; i++){if (head == NULL){head = p = new ListNode(a[i]);}else{p->next = new ListNode(a[i]);p = p->next;}}return head;}int main(){int a[]={1,1,2,3,3};int b[]={1,1,1};printList(deleteDuplicates(createList(a, sizeof(a)/sizeof(int))));printList(deleteDuplicates(createList(b, sizeof(b)/sizeof(int))));return 0;}
C++ solution by pezy/LeetCode
struct ListNode {int val;ListNode *next;ListNode(int x) : val(x), next(NULL) {}};class Solution {public:ListNode *deleteDuplicates(ListNode *head) {for (ListNode *cur = head; cur && cur->next; ){if (cur->val == cur->next->val){ListNode *del = cur->next;cur->next = del->next;delete del;}else cur = cur->next;}return head;}};
C++ solution by liuyubobobo/Play-Leetcode
/// Source : https://leetcode.com/problems/remove-duplicates-from-sorted-list//// Author : liuyubobobo/// Time : 2020-04-02#include <iostream>using namespace std;/// Linear Scan/// Time Complexity: O(n)/// Space Complexity: O(1)/// Definition for singly-linked list.struct ListNode {int val;ListNode *next;ListNode(int x) : val(x), next(NULL) {}};class Solution {public:ListNode* deleteDuplicates(ListNode* head) {ListNode* cur = head;while(cur && cur->next){if(cur->val == cur->next->val) cur->next = cur->next->next;else cur = cur->next;}return head;}};int main() {return 0;}