题目描述
给你一个链表,链表长度为n,链表内各元素为a1,a2....an,给你一个数m,求链表倒数第m个数是多少。
本题是附加代码模式,主函数main的代码会自动附加在同学们提交的代码后面,请同学们在提交的时候注释掉自己的main函数。
main函数代码如下:
int main()
{
// freopen("/config/workspace/answer/in.txt","r",stdin);
int n;
cin >> n;
List list;
InitList(list);
for(int i=0;i<n;i++){
int v;
cin >> v;
int r = AddNode(list,v);
if(r != 0) cout<<"add node failed"<<endl;
}
// PrintList(list);
int m;
cin >> m;
Node* result = FindMthNode(list,m);
if(result == NULL){
cout << "failed to find the node" <<endl;
}else{
cout << result->data << endl;
}
DestroyList(list);
return 0;
}
输入格式
第一行:链表长度n(1<=n<=1e4)
第二行:n个数字,为链表元素从头到尾依次排列
第三行:数字m
输出格式
输出倒数第m个元素的值并输出换行
输入样例
5
1 2 3 4 5
5
输出样例
1
数据范围与提示
//单链表的结构体定义和相应的操作函数如下图所示:
#include <iostream>
#include <cstdio>
using namespace std;
struct Node{
int data;
Node *next;
};
typedef Node* List;
int InitList(List& list){
return 0;
}
int DestroyList(List& list){
return 0;
}
int AddNode(List& list,int v){
return 0;
}
void PrintList(const List& list){
}
// 查找倒数第m个节点
Node* FindMthNode(const List& list, int m){
}
完整代码展示
#include<iostream>
#include<cstdio>
using namespace std;
struct Node{
int data;
Node *next;
};
typedef Node* List;
int InitList(List& list){
list=new Node;
list->next=NULL;
return 0;
}
int DestroyList(List& list){
List p1,p2;
p1=list;
p2=list;
while(p1!=NULL){
p1=p1->next;
free(p2);
p2=p1;
}
return 0;
}
int AddNode(List& list,int v){
List head=list;
List p1=list;
List p2=new Node;
p2->data=v;
p2->next=NULL;
if(head==NULL){
head->next=p2;
}
else{
while(p1->next!=NULL){
p1=p1->next;
}
p1->next=p2;
}
return 0;
}
Node* FindMthNode(const List& list,int m){
List p1=list;
int count=0;
while(p1->next!=NULL){
count++;
p1=p1->next;
}//计算链表长度
int target=count-m;//把倒数换成正数
int temp=0;
List p2=list->next;
while(temp!=target){
p2=p2->next;
temp++;
}
return p2;
}
//以下为附加代码
// int main(){
// int n;
// cin>>n;
// List list;
// InitList(list);
// for(int i=0;i<n;i++){
// int v;
// cin>>v;
// int r=AddNode(list,v);
// if(r!=0) cout<<"add node failed"<<endl;
// }
// int m;
// cin>>m;
// Node* result=FindMthNode(list,m);
// if(result==NULL){
// cout<<"failed to find the node"<<endl;
// }
// else{
// cout<<result->data<<endl;
// }
// DestroyList(list);
// return 0;
// }