问题 D: 案例3-1.3:求链表的倒数第m个元素(附加代码模式)

题目描述

给你一个链表,链表长度为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

输出样例  

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;
// }

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值