剑指offer 57. 删除链表中重复的结点

  1. 题目:在一个排序的链表中,存在重复的结点,请删除该链表中重复的结点,重复的结点不保留,返回链表头指针。 例如,链表1->2->3->3->4->4->5 处理后为 1->2->5
  2. 思路:
    1. 当我们碰到一个节点,往后看下一个,是不是和他相同,如果相同,那么一直往后找到不同于这个值的点,作为当前点
  3. 代码:
    /*
    struct ListNode {
        int val;
        struct ListNode *next;
        ListNode(int x) :
            val(x), next(NULL) {
        }
    };
    */
    class Solution {
    public:
        ListNode* deleteDuplication(ListNode* pHead)
        {
            ListNode* head = pHead;
            ListNode* preNode = NULL;
            if (!pHead)
                return NULL;
            while(pHead && pHead->next) {
                //cout << "pHead" << pHead->val << endl;
                //当我们碰到一个节点,往后看下一个,是不是和他相同,如果相同,那么一直往后找到不同于这个值的点,作为当前点
                if (pHead->next) {
                    if (pHead->next->val == pHead->val) {
                        ListNode* temp = pHead;
                        while (temp && temp->val == pHead->val) {
                            temp = temp ->next;
                        }
                        if (preNode)
                            preNode->next = temp;
                        else
                            head = temp;
                        pHead = temp;
                    } else {
                        preNode = pHead;
                        pHead = pHead -> next;
                    }
                }
            }
            return head;
        }
    };
发布了141 篇原创文章 · 获赞 5 · 访问量 7470

猜你喜欢

转载自blog.csdn.net/Alexia23/article/details/104094187
今日推荐