【剑指Offer】56.删除链表中重复的结点(Python实现)

题目描述

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

解法一:指针法

# -*- coding:utf-8 -*-
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None
class Solution:
    def deleteDuplication(self, pHead):
        first = ListNode(-1)
        first.next = pHead
        last = first
        while pHead and pHead.next:
            if pHead.val == pHead.next.val:
                val = pHead.val
                while pHead and val == pHead.val:
                    pHead = pHead.next
                last.next = pHead
            else:
                last = pHead
                pHead = pHead.next
        return first.next

解法二:栈方法

class Solution:
    def deleteDuplication(self, pHead):
        # write code here
        if not pHead:
            return pHead
        node_stack = []
        curVal = pHead.val
        node_stack.append(pHead)
        node = pHead.next
        while node:
            if node.val == curVal:
                n = node_stack.pop()
                while node.val == curVal:
                    node = node.next
                    if not node:
                        break
            else:
                node_stack.append(node)
                curVal = node.val
                node = node.next
        phead = ListNode(-1)
        head = phead
        while node_stack:
            node = node_stack.pop(0)
            head.next = node
            head = head.next
        head.next = None
        return phead.next
发布了101 篇原创文章 · 获赞 73 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/qq_36936730/article/details/104769033