找单链表中倒数第K个元素

//找单链表中倒数第K个元素,不保证存在,找不到,相关函数返回-1
//思路:
//第一个游标在第一个元素处,另一个在第一个元素处开始右移,看看能不能使两个游标形成 最后一个与倒数第K个 的状态
//若能,两个游标同时右移,直到右边游标到达末尾,这时第一个游标处就是所求元素处
//若不能,返回-1
#include <stdio.h>
#include <stdlib.h>
#define k 4
struct node{
    int  data;
    struct node *next;
};
struct node* Insert(struct node*head,int element)//相同的,插到后面
{
    //findprevious and insert element after the position found;
    struct node* t=head;

    while(t->next!=NULL&&t->next->data<=element)
        t=t->next;

    struct node *p;
    p=(struct node*)malloc(sizeof(struct node));
    p->data=element;
    p->next=t->next;
    t->next=p;

    return head;
};
int FindKthFromEnd(struct node* head)
{
    struct node *temp,*t;
    int count;
    temp=head->next;
    t=head->next;
    count=1;
    while(count<=k&&temp){
        temp=temp->next;
        count++;
    }
    if(count<k)
        return -1;
    while(temp){
        t=t->next;
        temp=temp->next;
    }
    return t->data;

}
int main(){
    //申请表头
    struct node *head;
    head=(struct node *)malloc(sizeof(struct node));
    head->next=NULL;
    //插入元素
    for(int i=1;i<=10;i++)
        head=Insert(head,i);//以10为例
    int number=FindKthFromEnd(head);
    printf("%d\n",number);
    return;
}

//C++实现
#include <cstdio>
#include <iostream>
#include <vector>
using namespace std;
vector <int> array;
int main(){
	int k,number;
	int len;
	cin>>k;
	while(scanf("%d",&number)!=EOF&&number>=0)
		array.push_back(number);
    len=array.size();
	if(k<=0||len<k)
		cout<<"NULL\n";
	else
		cout<<array[len-k]<<'\n';
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值