剑指offer:删除链表中重复的节点

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

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

class Solution:
    def deleteDuplication(self, head):
        """
        给定一个有序的链表,删除所有重复的节点
        """
        # 我们先设置一个辅助节点
        # begin用来定位在返回链表的头节点的前一个节点(辅助节点)上
        # pre_node用来定位返回链表的尾节点
        begin = pre_node = ListNode(0)
        while head:
            c = 0  # 当前值出现的次数,初始化为0可以使后续代码更简洁
            val = head.val  # 当前值
            # 记录当前节点,因为无论如何,head都会往前移动一次,当下面这个while退出之后,
            # cur != head
            cur = head
            # 当前值连续出现的次数
            while head and head.val == val:
                c += 1
                head = head.next
            # 如果当前值只连续出现过1次,说明不是重复节点,需要将当前节点添加到链表的末尾
            # 由于pre_node是定位尾节点的,所以每次添加一个尾节点的时候,需要将原尾节点(pre_node)
            # 和新的尾节点连接起来,然后将pre_node重新定位到链表的尾节点
            if c == 1:
                pre_node.next = cur
                pre_node = pre_node.next

        # 当遍历完整个链表之后,注意要将尾节点与Null连接起来
        pre_node.next = None
        # begin在头节点的前一个节点(辅助节点)上,因此返回begin.next
        return begin.next

猜你喜欢

转载自blog.51cto.com/jayce1111/2382980