案例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> v;
        int r = AddNode(list,v);
        if(r != 0) cout<<"add node failed"<> m;
    Node* result = FindMthNode(list,m);
    if(result == NULL){
        cout << "failed to find the node" <data << endl;
    }
    DestroyList(list);
    return 0; 
}
输入

第一行:链表长度n(1<=n<=1e4)
第二行:n个数字,为链表元素从头到尾依次排列
第三行:数字m

输出

输出倒数第m个元素的值并输出换行

样例输入
5
1 2 3 4 5
5 
样例输出
1
提示

单链表的结构体定义和相应的操作函数如下图所示:

#include  
#include 
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 
#include 
#include 
using namespace std;

struct Node {
    int data;
    Node *next;
};
typedef Node* List;

int InitList(List& list) {
    list = (Node*)malloc(sizeof(Node));  // 分配头结点
    list->next = NULL;  // 头结点的next指针为空
    return 0;
}

int AddNode(List& list, int v) {
    Node *p = list;  // 从头结点开始遍历
    while (p->next != NULL) {
        p = p->next;  // 遍历到链表的最后一个节点
    }
    Node *newNode = (Node*)malloc(sizeof(Node));  // 创建新节点
    newNode->data = v;  // 设置节点的数据
    newNode->next = NULL;  // 新节点的next指针为空
    p->next = newNode;  // 将最后一个节点的next指针指向新节点
    return 0;
}

// 查找倒数第m个节点
Node* FindMthNode(const List& list, int n, int m) {
    if (m > n) {
        return NULL;  // 如果m大于链表长度,返回NULL
    }
    
    Node* p = list->next;  // 从第一个节点开始
    for (int i = 1; i <= n - m; i++) {
        p = p->next;  // 遍历到倒数第m个节点
    }
    return p;
}

int main() {
    int n;
    cin >> n;
    List list;
    InitList(list);  // 初始化链表
    
    for (int i = 0; i < n; i++) {
        int v;
        cin >> v;
        AddNode(list, v);  // 添加节点
    }

    int m;
    cin >> m;
    
    Node* result = FindMthNode(list, n, m);  // 查找倒数第m个节点
    if (result == NULL) {
        cout << "failed to find the node" << endl;
    } else {
        cout << result->data << endl;  // 输出倒数第m个节点的数据
    }
    
    return 0;
}

你可能感兴趣的:(链表,数据结构)