[leetcode题解]83.Remove Duplicates from Sorted List(排序链表去重)

题目给定一个单链表,该单链表已排序,要求删除所有重复值的节点。因为链表已排序,所以相同的值的节点都相邻,所以本题是相邻节点去重问题,可以直接两个指针操作即可。比较简单的排序链表去重问题。一种逐个去重,一种把所有重复的找出来,直接去除所有重复元素,两种方法分别是python实现和c++实现。

python代码:

class Solution(object):
    def deleteDuplicates(self, head):
        """
        :type head: ListNode
        :rtype: ListNode
        :author: 凌风技术站-iaccepted
        """
        if head is None or head.next is None:
            return head
        p = head
        q = head.next
        while q is not None:
            if p.val == q.val:
                p.next = q.next
                q = p.next
            else:
                p = p.next
                q = q.next
        return head

c++代码:

class Solution {
public:
    ListNode* deleteDuplicates(ListNode* head) 
    {
    	//author:凌风技术站-iaccepted
        if (head == NULL)return head;
        ListNode *p = head, *q = NULL;
        
        while(p != NULL)
        {
            q = p->next;
            while(q != NULL && q->val == p->val)q = q->next;
            p->next = q;
            p = q;
        }
        return head;
    }
};

本文遵从CC3.0协议转载请注明:转自凌风技术站

本文标题:[leetcode题解]83.Remove Duplicates from Sorted List(排序链表去重)

本文链接地址:http://www.iaccepted.net/algorithm/leetcode/86.html

相关文章



发表评论

电子邮件地址不会被公开。 必填项已用*标注