【done】剑指offer——面试题15:链表中倒数第k个结点

力扣,https://leetcode.cn/problems/lian-biao-zhong-dao-shu-di-kge-jie-dian-lcof/description/

class Solution {
    public ListNode trainingPlan(ListNode head, int cnt) {
        if (head == null) {
            return null;
        }
        ListNode i = head, j = head;
        int step = cnt;
        while (step > 0) {
            if (j == null) { // 增加cnt > 链表长度情况的处理
                return null;
            }
            j = j.next;
            --step;
        }
        while (j != null) {
            i = i.next;
            j = j.next;
        }

        return i;
    }
}

Solution1:

典型的双指针题目。但要考虑到很多边界条件!
注意此题中陷阱很多,具体看书中解释
20181008修改代码

/*
struct ListNode {
	int val;
	struct ListNode *next;
	ListNode(int x) :
			val(x), next(NULL) {
	}
};*/
class Solution {
public:
    ListNode* FindKthToTail(ListNode* pListHead, unsigned int k) {
        struct ListNode* p1 = pListHead,*p2=pListHead;
        int abs_k = k;
        if (!k) return NULL;
        while (--abs_k > 0) {
            if (!p2 || !p2->next)
                return NULL;
            p2 = p2->next;
        }
        while (p2->next != NULL) {
            p1 = p1->next;
            p2 = p2->next;
        }
        return p1;
    }
};

原答案

/*
struct ListNode {
	int val;
	struct ListNode *next;
	ListNode(int x) :
			val(x), next(NULL) {
	}
};*/
class Solution {
public:
    ListNode* FindKthToTail(ListNode* pListHead, unsigned int k) {
        struct ListNode* p1 = pListHead,*p2=pListHead;
        int abs_k=k;
        if(k==0) return NULL;
        while(--abs_k>0){
            if(p2 == NULL || p2->next == NULL)
                return NULL;
            p2=p2->next;
        }
        while(p2->next!=NULL){
            p1=p1->next;
            p2=p2->next;
        }
        return p1;
    }
};
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值