题目描述:
设计一个算法求出单链表的倒数第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;
}