leetcode_ 83. 删除排序链表中的重复元素python

题目描述

给定一个排序链表,删除所有重复的元素,使得每个元素只出现一次。

示例 1:

输入: 1->1->2
输出: 1->2

示例 2:

输入: 1->1->2->3->3
输出: 1->2->3

思想:
没啥好说的,就是个简单的删除重复元素,掌握链表的删除操作就行了,声明一个临时变量,两个作为比较的指针。
leetcode_ 83. 删除排序链表中的重复元素python

代码:

# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution(object):
    def deleteDuplicates(self, head):
        """
        :type head: ListNode
        :rtype: ListNode
        """
        if (head == None)or(head.next == None):
            return head
        tem = head.val
        #指前面的指针
        p = head
        #指后面的指针
        q = head.next
        #比较,删除操作
        while q:
            if q.val == tem:
                p.next = q.next
                q = q.next
            else:
                p = p.next
                q = q.next
                tem = p.val
        return head