14-链表中倒数第k个节点

知识点:链表

一、题目描述:

输入一个链表,输出该链表中倒数第k个结点。

二、解题思路:

1:利用双指针

以链表1->2->3->4->5->6,k=3为例:

C++实现:

class Solution {
public:
    ListNode* FindKthToTail(ListNode* pListHead, unsigned int k) {
        ListNode *p = pListHead;
        ListNode *q = pListHead;
        int i = 0;
        while(p!=NULL){//遍历链表,当i>=k,指针p和q同时走
            if(i >= k)
            {
                q = q->next;
            }
            p = p->next;
            
            i++;
        }
        return i<k? NULL: q;//当i<k的时候指针q指向的是头结点,所以返回NULL
    
    }
};

python:

# -*- coding:utf-8 -*-
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def FindKthToTail(self, head, k):
        # write code here
        p = head;
        q = head;
        index = 0;
        
        while p!=None:
            if index >= k:
                q = q.next
            p = p.next
            index += 1
        return None if index < k else q

 

2:两次遍历。第一次遍历获取链表长度n,第二次遍历链表获取第n-k+1个节点(索引从0开始),即倒数第k个节点。

C++实现:

class Solution {
public:
    ListNode* FindKthToTail(ListNode* pListHead, unsigned int k) {
        /*
        if(pListHead== NULL || k<0){
            return NULL;
        }
        */
        //获取链表长度n
        ListNode* p;
        ListNode* q;
        p = pListHead;
        q = pListHead;
        int n = 0;
        while(p!=NULL){
            n++;
            p = p->next;
        }
        if(k>n){//需要判断是否越界
            return NULL;
        }
        
        //n-k+1个节点
        for(int i=0; i<n-k; i++){
            q = q->next;
        }
        return q;
    
    }
};

python实现:

class Solution:
    def FindKthToTail(self, head, k):
        # write code here
        if head==None or k<=0:
            return None

        p = head
        q = head
        
        #获取链表长度n
        n = 0
        while p!=None:#C++中的NULL,在python中为None
            n += 1
            p = p.next#C++中->
        if k>n:
            return None
        
        #获取第n-k+1个节点
        '''
        #while循环
        cnt=0
        while q!=None:
            cnt += 1
            if cnt==n-k+1:
                return q
            q=q.next
        '''
        #用for循环
        for i in range(0,n-k):#range(0,n-k+1)错误,range(1,n-k+1)正确
            q = q.next
        return q
       

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值