剑指offer(14)

题目描述
输入一个链表,输出该链表中倒数第k个结点。
时间限制:1秒 空间限制:32768K

方法1:首先遍历所有结点,记录结点总个数,然后第二次遍历直接寻找到第(总个数-k)个结点即为倒数第k个结点。

include <stdlib.h>
include <vector>
include <stack>
include <math.h>
include <iostream>

using namespace std;

struct ListNode {
    int val;
    struct ListNode *next;
    ListNode(int x) :
            val(x), next(NULL) {
    }
};
class Solution {
public:
    ListNode* FindKthToTail(ListNode* pListHead, unsigned int k) {
        int count=0,n=0;
        ListNode *t=pListHead;

        while(t!=NULL){
            count++;
            t=t->next;
        }

        n=count-k;
        t=pListHead;

        if(k>count)
            return NULL;
        else
            if(n>=0){
                while(n--){
                    t=t->next;
                }
            }
        return t;
    }
};

int main() {
    Solution s;

    struct ListNode* p=(struct ListNode*)malloc(sizeof(struct ListNode));
    struct ListNode* r=(struct ListNode*)malloc(sizeof(struct ListNode));

    p->val=0;
    p->next=NULL;

    for(int i=1000;i>=1;i--){
        struct ListNode* temp=(struct ListNode*)malloc(sizeof(struct ListNode));
        temp->val=i;
        temp->next=p->next;
        p->next=temp;
    }

    r=s.FindKthToTail(p,1);
    cout<<r->val<<endl;

        return 0;
}

方法2:利用两个指针,第一次利用一个指针遍历链表中的前k个,第二次遍历剩下的元素的同时利用第二个指针遍历链表一遍,即为倒数第k个结点的元素。

class Solution {
public:
    ListNode* FindKthToTail(ListNode* pListHead, unsigned int k) {
        ListNode *p1=pListHead;
        ListNode *p2=pListHead;

        if(p1==NULL)
            return NULL;

        for(int i=0;i<k-1;i++){
            if(p1->next==NULL)
                return NULL;
            p1=p1->next;
        }

        while(p1->next!=NULL){
            p1=p1->next;
            p2=p2->next;
        }

        return p2;

    }
};

参考博客:https://blog.csdn.net/u013686654/article/details/73827816
https://blog.csdn.net/xiaomei920528/article/details/74330489

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值