Question

在一个排序的链表中,存在重复的结点,请删除该链表中重复的结点,重复的结点不保留,返回链表头指针。 例如,链表1->2->3->3->4->4->5 处理后为 1->2->5

Solution

  • 链表的题目一般都会考虑用一个额外的节点,因为第一个节点可能重复了,那么会被删除,重复的节点需要全部删除,那么需要设置一个先前节点的指针。然后把思路理清楚,就可以得到正确答案了。

Code

/*
struct ListNode {
    int val;
    struct ListNode *next;
    ListNode(int x) :
        val(x), next(NULL) {
    }
};
*/
class Solution {
public:
    ListNode* deleteDuplication(ListNode* pHead) {
		if (pHead == NULL)
            return pHead;
        
        ListNode* first = new ListNode(-1);
        first->next = pHead;
        
        ListNode* pre = first;
        while (pHead) {
            ListNode* tmp = pHead;
            while (tmp->next != NULL && tmp->val == tmp->next->val)
                tmp = tmp->next;
            if (tmp == pHead) {
                pre = pHead;
                pHead = pHead->next;
            }

            if (tmp != pHead && tmp != NULL) {
				pre->next = tmp->next;
                pHead = pre->next;
            }
        }
        
        return first->next;
    }
};

相关文章:

  • 2022-12-23
  • 2021-06-04
  • 2022-02-01
  • 2021-07-16
  • 2022-12-23
  • 2021-06-29
  • 2021-10-31
猜你喜欢
  • 2021-11-03
  • 2021-07-17
  • 2021-11-14
  • 2021-10-18
  • 2021-10-03
  • 2022-12-23
相关资源
相似解决方案