diff --git a/83. Remove Duplicates from Sorted List.md b/83. Remove Duplicates from Sorted List.md new file mode 100644 index 0000000..e3632dd --- /dev/null +++ b/83. Remove Duplicates from Sorted List.md @@ -0,0 +1,34 @@ +# [83. Remove Duplicates from Sorted List](https://leetcode.com/problems/remove-duplicates-from-sorted-list/description/) +# 思路 +去除链表中的重复元素。 +设置两个相邻的指针pre和p,pre代表已处理部分的最后一个节点,p代表待处理节点,比较pre和p的值来决定是否删除p; +# C++ +``` +/** + * 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) { + if(head == NULL) return head; + ListNode *pre = head, *p = head -> next, *dup; // dup是待删除的重复节点 + while(p){ + while(p !=NULL && p -> val == pre -> val){ // 若p的值等于pre的值 + pre -> next = p -> next; // 指针跳过p + dup = p; + dup -> next = NULL; + delete dup; + p = pre -> next; // p指针后移 + } + pre = p; // pre后移 + if(p) p = p -> next; + } + return head; + } +}; +```