总结:和链表有关面试题

面试中被问链表的题目我就不再多说,直接总结题目。

1、将链表逆序

这个问题很早就研究过,但后来一次面试的时候我突然紧张忘了,没答上来。

我不知道大家的解法是什么,我的解法是遍历链表是用前插发插入节点,最后的链表就是逆序的。

class ListNode:
    def __init__(self, x):
        self.val = x
        self.next = None
class Solution:
  
    def resverse(self, head):
        print id(head)
        if None == head or None == head.next:
            return head
        p = head.next
        head.next = None
        while None != p:
           q = p.next
           p.next = head
           head = p
           p = q
        return head

2、判断链表中是否有环

这个问题似乎是有固定的解法即就是设置快、慢两个指针,若指针能相遇,则说明有环,如果慢指针为 None了,就说明没有环

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

    def hasCycle(self, head):
        if None == head or None == head.next:
            return False
        p = head
        q = head.next
        while q != None and p != q:
            p = p.next
            q = q.next
            if None != q:
                q = q.next
        return p == q

3、既然链表中有环,求取环的长度

仔细想想,这其实和我们小学的追击问题是一样的,甲乙相遇的条件是 S甲 - S2 = n * 周长。另外,因为已经找到了环上的一个点,那么直接从该点开始,下次到该点时所走长度就是环的长度。

class Solution:

    def cycleLen(self, head):
        if None == head or None == head.next:
            return 0
        p = head
        q = head.next
        while q != None and p != q:
            p = p.next
            q = q.next
            if None != q:
                q = q.next
        if p != q:
            return 0
        ret_len = 1
        p = p.next
        while p != q:
            ret_len += 1
            p = p.next
        return ret_len



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值