1.用双指针一前一后去遍历链表,如果他们指向的结点数值相等,则消除前面那个结点。
/** * 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==NULL||head->next==NULL) return head; ListNode* f1=head,*f2=head->next; while(f2!=NULL) { if(f1->val==f2->val) { f2=f2->next; f1->next=f2; } else { f1=f1->next; f2=f2->next; } } return head; } };
2、优化一下,直接用一个指针去遍历即可,用f替换f1,f->next替换f2
/** * 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==NULL||head->next==NULL) return head; ListNode* f=head; while(f->next!=NULL) { if(f->val==f->next->val) f->next=f->next->next; else f=f->next; } return head; } };