题解 | #删除链表中重复的结点#

删除链表中重复的结点

http://www.nowcoder.com/practice/fc533c45b73a41b0b44ccba763f866ef

新建头结点,处理首元素特例!

class Solution {
public:
    ListNode* deleteDuplication(ListNode* pHead) {
        
        
        // 这个方法问题有点大,卡死在第一个元素
        // 解决方案:新建头结点
        ListNode *head = (ListNode *)malloc(sizeof(ListNode));
        ListNode *pre = head;
        head->next = pHead;
        ListNode *cur = pHead;
        
        int flag = -1;
        
        // 有一个特殊情况,第一个元素是多个,这个无法解决
        while(cur != NULL){
            if(cur->next == NULL){
                break;
            }
            
            if(cur->val == cur->next->val){
                cur = cur->next;
                flag = 1;
            }else{
                cur = cur->next;
                
                if(flag == 1){
                    pre->next = cur;
                    flag = -1;
                }else{
                    pre = pre->next;
                }
            }
            
            // 如果flag没被改变,说明后面所有元素一致,需要处理
            if(flag == 1){
               pre->next = cur->next;
            }
        }
        
        return head->next;
    }
};
全部评论

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务