每日一题(3)

判断一个链表是否带环

class Solution {
public:
    bool hasCycle(ListNode **head) {
        if(head==NULL)
            return false;
        ListNode *fast=head;
        ListNode *slow=head;
        while(fast && fast->next){
            fast=fast->next->next;
            slow=slow->next;
            if(fast==slow)
                return true;
        }
        return false;
    }
};

在一个排序的链表中,存在重复的节点,请删除该链表中重复的节点,重复的节点不保留,返回链表头指针


解决这个问题的第一步是确定删除函数的参数。当然这个函数需要输入带删除链表的头节点。头节点可能与后面的节点重复,也就是说头节点也可能被删除,因此删除函数形参应该声明为二级指针

class Solution {
public:
    ListNode* deleteDuplication(ListNode* pHead)
    {
        if(pHead || *pHead)
            return NULL;
        ListNode *list=NULL;
        ListNode *node=*pHead;
        while(node){
            bool ret=false;
            ListNode *cur=node->next;
            if(cur && node->val==cur->val)
                ret=true;
            if(!ret){
                list=node;
                node=node->next;
            }else{
                int value=node->val;
                ListNode *p=node;
                while(p!=NULL && p->val==value){
                    cur=p->next;
                    delete p;
                    p=NULL;
                    p=cur;
                }
                if(list==NULL)
                    *pHead=cur;
                else
                    list->next=cur;
                node=cur;
            }
        }
        return list;
    }
};

猜你喜欢

转载自blog.csdn.net/sifanchao/article/details/81366278