题目描述

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

时间限制:1秒;空间限制:32768K;本题知识点:链表

解题思路

# -*- coding:utf-8 -*-
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None
class Solution:
    def deleteDuplication(self, pHead):
        # write code here
        p0 = ListNode(0) #创建一个新的头节点
        p = p0 #中间节点p,用来存储前一个节点
        p0.next = pHead
        while pHead!=None and pHead.next!=None:
            # 如果存在连续相等的节点,全部跳过(删除)
            if pHead.val==pHead.next.val:
                val = pHead.val #利用val进行判断
                while pHead!=None and pHead.val==val:
                    pHead = pHead.next
                p.next = pHead
            # 找到一个不存在连续相等的节点,更新p位置
            else:
                p = pHead
                pHead = pHead.next
        return p0.next

 

相关文章:

  • 2021-07-17
  • 2021-11-14
  • 2021-10-18
  • 2022-12-23
  • 2021-10-03
  • 2022-12-23
猜你喜欢
  • 2021-06-04
  • 2021-07-16
  • 2022-12-23
  • 2021-07-09
  • 2021-06-01
  • 2021-06-11
  • 2021-11-03
相关资源
相似解决方案