从链表中删除重复节点

问题描述(LeetCode):
Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list.
For example,
Given 1->2->3->3->4->4->5, return 1->2->5.
Given 1->1->1->2->3, return 2->3.

意思就是只要有重复的节点都去掉。这主要考察的是链表删除节点的操作,以及考虑问题的是否周全。

大致思路如下:
1 定义一个当前节点指针cur,只要一判断到某节点和其之后的节点的值相同,就用一个变量把该值保存下来,然后从当前节点开始,把所有相同值的节点都删除掉;
2 为了拼接由于1中删除节点产生的断层,需要一个节点指针pre。只要判断出当前节点与它下一个节点的值不同,便可把当前节点指针赋值给pre。

代码如下(思路还是有点乱,思路清晰的话,代码应该可以优化):

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* deleteDuplicates(ListNode* head) {
        if(head == NULL || head->next == NULL)
            return head;
        int temp = 0;
        ListNode* cur = head;
        head = NULL;
        ListNode* pre = head;
        while(cur != NULL)
        {
            if(cur->next == NULL)
                break;
            if(cur->val != cur->next->val)
            {
                if(head == NULL)
                    head = cur;
                pre = cur;
                cur = cur->next;
            }
            else
            {
                temp = cur->val;
                while(cur != NULL && cur->val == temp)
                {
                    ListNode *temp = cur;
                    cur = cur->next;
                    delete temp;
                }
                if(pre == head && head == NULL)
                {
                    pre = cur;
                }
                else
                    pre->next = cur;
            }
        }
        if(cur != NULL && head == NULL)
            head = cur;
        return head;
    }
};

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值