链表问题 leetcode心得

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

class Solution(object):
    def delete(self,node):     #删除某节点
        node.value=node.next.value
        node.next=node.next.next

    def delete_n(self,head,n):   #删除倒数n的节点 (双指针等距离移动的思想)
        p=q=head
        for i in range(n):
            p=p.next
        if not p:
            return head.next
        while p.next:
            p=p.next
            q=q.next
        q.next=q.next.next
        return head

    def reserve(self,head):    #链表的反转
        if not head or not head.next:
            return head
        p=self.reserve(head.next)
        head.next.next=head
        head.next=None
        return head

    def merge(self,l1,l2):    #链表按从小到大合并
        head=Node(0)
        p=head
        while l1 and l2:
            if l1.value<l2.value:
                p.next=l1
                l1=l1.next
            else:
                p.next=l2
                l2=l2.next
            p=p.next
        if l1:
            p.next=l1
        if l2:
            p.next=l2
        return head.next

    def huiwen(self,head):    #回文链表(利用列表方法)
        p=head
        result=[]
        while p:
            result.append(p.value)
            p=p.next
        return result==result[::-1]

    def hunaxing(self,head):   #利用快慢法
        slow=fast=head
        while fast or fast.next:
            fast=fast.next.next
            slow=slow.next
            if fast==slow:
                return True
        return False




猜你喜欢

转载自blog.csdn.net/weixin_38740463/article/details/87881305