Algorithm(链表第后k个数)

题目描述:

设计一个算法求出单链表的倒数第m个结点,要求不能求出链表长度,不得对链表进行旋转,如果找到这样的结点就返回它的地址,如果没有就返回NULL。

分析:编程不难,主要就是思路。我们可以设置两个节点p,q,让p从*head位置先移动m-1个结点,然后q开始移动,当p移动到尾指针时,返回q就可以。

代码如下:

#include <iostream>
#include<string>
#include<cstdlib>
using namespace std;
typedef struct node* Node;
struct node
{
    int val;
    node *next;
    node(int v=0,node *n=nullptr):val(v),next(n){}
};
Node create(int n)
{
    cout<<"please input elements for list:\n";
    Node q=new node;
    Node p=q;
    for(int i=0;i<n;++i)
    {
        int value;
        cin>>value;
        Node temp=new node(value);
        p->next=temp;
        p=temp;
    }
    p->next=nullptr;
    return q;
}
int getm(Node li,int m)
{
    Node p=li,q=li;
    for(int i=0;i<m;++i)
    {
       p=p->next;
       if(p==nullptr&&i<m-1)
           throw "the size of list is too small";
    }
    //if(p->next==nullptr)
       //     return q->next->val;
    while(p->next!=nullptr)
    {
        q=q->next;
        p=p->next;
    }
    return q->next->val;
}
int main()
{
    int n,m;
    cout<<"please input the size of list:";
    cin>>n;
    Node head=create(n);
    cout<<"please input m:";
    cin>>m;
    try{
        cout<<getm(head,m)<<endl;
       }
    catch(string err)
    {
        cerr<<err<<endl;
        exit(1);
    }
    return 0;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值