剑指OFFER-链表中倒数第k个结点

剑指OFFER-链表中倒数第k个结点

Question

输入一个链表,输出该链表中倒数第k个结点。
关键词:链表 顺序

Solution

暴力遍历

顺序遍历所有结点得到链表总长度,再顺次得到倒数第k个节点。另外可以利用栈,先压入所有结点,然后推出第k个结点。
时间复杂度:O(2N)
空间复杂度:O(1)

  • Python
class Solution:
    def FindKthToTail(self, head, k):
        if not head or k==0:
            return None
        count = 0
        chead = head
        while head:
            head = head.next
            count += 1
        if k>count:
            return None
        for i in range(count-k):
            chead = chead.next
        return chead
  • C++
class Solution {
public:
    ListNode* FindKthToTail(ListNode* pListHead, unsigned int k) {
        if (!pListHead || k==0)
            return NULL;
        int count = 0;
        ListNode* save = pListHead;
        while(pListHead){
            count += 1;
            pListHead = pListHead->next;
        }
        if(k>count)
            return NULL;
        for(int i = 0; i < count - k; i++)
            save = save->next;
        return save;
    }
};

先跑与后跑

A结点先跑k-1步,B结点再出发,由于AB距离为k-1,当A跑到尾端时,B正好处于倒数第k个结点上。
时间复杂度:O(N)
空间复杂度:O(1)

  • Python
class Solution:
    def FindKthToTail(self, head, k):
        if not head or k==0:
            return None
        tail = head
        for i in range(k-1):
            if tail.next:
                tail = tail.next
            else:
                return None
        while tail.next:
            head, tail = head.next, tail.next
        return head
  • C++
class Solution {
public:
    ListNode* FindKthToTail(ListNode* pListHead, unsigned int k) {
        if (!pListHead || k==0)
            return NULL;
        ListNode* a = pListHead;
        ListNode* b = pListHead;
        for(int i = 0; i < k-1; i++){
            if(a->next)
                a = a->next;
            else
                return NULL;
        }
        while(a->next){
            a = a->next;
            b = b->next;
        }
        return b;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值