Leetcode linkedList 83 delete duplicate elements in the sorted linked list

THE

problem

solution

Code


/*
思路:  因为这个链表本身就是有序的, 那么每次遍历到一个点的时候保存这个点的一个地址,然后向下走,

当下一个点的值等于这个点的值时候, 继续走,走到不等于的时候之前的地址直接指向这里,然后更新之前的地址到这。 

- 
- 
- - 
- - 
- 
*/
class Solution {
    
    
public:
   ListNode* deleteDuplicates(ListNode* head) {
    
    
       ListNode* p = new ListNode(0);
       p->next  = head;
       ListNode* pre = NULL;
       ListNode* current = NULL;
       int flag = 0;
       
       while(head&&head->next){
    
    
           if(head->val==head->next->val){
    
    
               if(!flag){
    
    
                   pre = head;
                   flag = 1;
               }
               current = head->next; 
               head = head->next;
               
               
           }
           else{
    
    
               
               if(current&&pre){
    
    
                   pre->next = current->next;
                   pre =  NULL;
                   current = NULL;
                   flag = 0;
               }
              
                   head = head->next;



           }
           
           
       

       }
       if(pre&&current)pre->next =NULL;
       return p->next;

   }
};


Summary and reflection

  1. Pay attention to solving some boundary phenomena.

Guess you like

Origin blog.csdn.net/liupeng19970119/article/details/114240871