常见算法解法——链表篇

链表

链表中每一个节点为一个对象,对象中包含两个成员变量,第一个是val,代表链表的值,第二个是next,它指向下一个节点,是下一个节点对象的引用。

定义链表

class ListNode:
    def __init__(self, x):
        self.val = x
        self.next = None

删除节点

给定链表中的某个节点,删除该节点

class Solution {
    public void deleteNode(ListNode node) {
        node.val = node.next.val;
        node.next = node.next.next;
    }
}

反转链表

普通方法:

def reverseList(head: Optional[ListNode]) -> Optional[ListNode]:
    newHead = None
    while head != None:
        temp = head.next
        head.next = newHead
        newHead = head
        head = temp
    return newHead

使用栈解决:
一定要注意让尾巴节点next指针为空,否则将形成环:

def reverseList(head: Optional[ListNode]) -> Optional[ListNode]:
    if head == None:
        return None
    a = []
    while head != None:
        a.append(head)
        head = head.next
    head = a.pop()
    b = head
    while len(a) > 0:
        n = a.pop()
        b.next = n
        b = n
    b.next = None

        return head

合并两个有序链表

合并两个升序链表,变成一个新的升序链表

递归:

def mergeTwoLists(self, list1: Optional[ListNode], list2: Optional[ListNode]) -> Optional[ListNode]:
    if list1 is None: return list2
    if list2 is None: return list1
    if list1.val <= list2.val:
        list1.next = self.mergeTwoLists(list1.next, list2)
        return list1
    else:
        list2.next = self.mergeTwoLists(list1,list2.next)
        return list2

判断链表是否有环

直观解法:

class Solution:
    def hasCycle(self, head: Optional[ListNode]) -> bool:
        a = []
        while head != None:
            if head not in a:
                a.append(head)
                head = head.next
            else:
                return True
        return False

快慢指针:

class Solution:
    def hasCycle(self, head: Optional[ListNode]) -> bool:
        head1 = head
        head2 = head
        while head1 != None and head2 != None and head2.next != None:
            head1 = head1.next
            head2 = head2.next.next
            if head1 == head2:
                return True
        return False
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

微笑小星

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值