剑指offer-面试题18删除链表中的节点-python

#-*- coding:utf-8 -*-
'''
description
    题目: 删除链表中的节点
    1.在O(1)时间内删除链表节点

'''


'''
这里我们首先定义一个链表的类

'''

class linkNode:
    def __init__(self, value, next = None):
        self.value = value
        self.next = next


class Solution:
    def delete_node_in_o1_time(self, p, head):
        '''
        :param p: linknode
        :return: None
        这里一共有三种情况: 节点是头节点且只有这一个节点
                          节点是尾节点
                          节点是链表中的某个节点
        '''
        if p == head and p.next is None:
            head = None
        if p.next is None:
            q = head
            while q.next is not p:
                q = q.next
            q.next = None

        q = p.next
        p.value = q.value
        p.next = q.next

    def print_lnode(self, head):
        p = head
        while p is not None:
            print(p.value)
            p = p.next

    def gen_lnode(self, lst):
        head = linkNode(lst[0])
        p = head
        for i in range(1, len(lst)):
            p.next = linkNode(lst[i])
            p = p.next
        return head

    def delete_repeat_node(self, head):
        #先添加一个节点,放在head之前最后再删了,其实也可以先找不重复的head差不多
        if head is None:
            return
        p = linkNode(-100)
        p.next = head
        q = head
        while q is not None and q.next is not None:
            if q.value == q.next.value:
                val = q.value
                p.next = p.next.next.next
                q = p.next
                while q is not None and q.value == val:
                    p.next = p.next.next
                    q = p.next
            else:
                p = p.next
                q = p.next
        return head




s = Solution()
head = s.gen_lnode([1,2,2,3,3,3,4])
# p = head.next.next
# s.delete_node_in_o1_time(p, head)
s.print_lnode(head)
s.delete_repeat_node(head)
s.print_lnode(head)

 

你可能感兴趣的:(剑指offer)