LeetCode remove-duplicates-from-sorted-list

题目描述

删除给出链表中的重复元素,使链表中的所有元素都只出现一次

例如:

给出的链表为1->1->2,返回1->2.

给出的链表为1->1->2->3->3,返回1->2->3.

 解题思路

/**
 * 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)
            return head;
        ListNode *p = head->next;
        ListNode *pre = head;
        while( p ){
            if(pre->val == p->val){
                pre->next = p->next;
                p = pre;
            }
            pre = p;
            p = p->next;
        }
        return head;
    }
};
发布了169 篇原创文章 · 获赞 9 · 访问量 4824

猜你喜欢

转载自blog.csdn.net/weixin_41317766/article/details/102229626