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

题目描述

在一个排序的链表中,存在重复的结点,请删除该链表中重复的结点,重复的结点不保留,返回链表头指针。 例如,链表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):
        # write code here
        if pHead==None or pHead.next==None:
            return pHead
        if pHead.val==pHead.next.val:
            node=pHead.next
            while node!=None and node.val==pHead.val:
                node=node.next
            return self.deleteDuplication(node)
        else:
            pHead.next=self.deleteDuplication(pHead.next)
            return pHead

用递归来做,如果下一个节点和现在没有重复,就递归到下一个节点,如果重复了,用一个node保存pHead.next,继续next到不重复了,递归到node结点,这样就把重复结点都跳过了。

猜你喜欢

转载自blog.csdn.net/gt362ll/article/details/82811395