删除且保留其中一个重复元素
思路:
遍历结点,遇到相同的跳过一个结点(删除)
def deleteDuplicates(self, head):if head == None:return headcur = headwhile cur.next != None:first = cur.valccur = cur.nextsecond = ccur.valif second == first:ccur = ccur.nextcur.next = ccurelse:cur = ccurreturn head
删除且不保留其中一个重复元素
思路:
双指针:快慢指针,用快指针找到相同的或者不同的值,并用flag标记,找到不同的值后用慢指针指向。
题目是不保留重复元素
def deleteDuplicates(self, head: ListNode) -> ListNode:dummy = ListNode(0)slow = dummyfast = headwhile fast != None:flag = Falsewhile fast.next !=None and fast.val == fast.next.val:flag = Truefast = fast.nextif not flag:slow.next = fastslow = slow.nextfast = fast.nextslow.next = Nonereturn dummy.next