您的位置:首页 > 其它

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

2016-10-27 23:00 239 查看
//找单链表中倒数第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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: