/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
/*本题思路简单,直接用两个指针pre和cur,分别指向当前指针的
前一个结点和当前结点,如果两个值相同,则删除当前结点,遍历整个链表。
参考自:https://github.com/soulmachine/leetcode*/
class Solution {
public:
ListNode *deleteDuplicates(ListNode *head) {
if(head == nullptr) return head;
ListNode *pre = head, *cur = pre->next;
if(cur == nullptr) return head;
for(;cur != nullptr; cur = cur->next){
if(cur->val == pre->val){
pre->next = cur->next;
delete cur;
}
else{
pre = pre->next;
}
}
return head;
}
};
LeetCode之Remove Duplicates from Sorted List
最新推荐文章于 2019-04-24 11:20:17 发布