题目:
代码:
#include<iostream>
using namespace std;
//链表节点结构体定义
struct ListNode
{
int val;
ListNode *next;
ListNode(int x):val(x),next(NULL){}
};
//构建链表
void getList(int n,ListNode *dummyHead)
{
//定义一个指向当前节点的指针 cur,刚开始指向虚拟头结点。
ListNode *cur=dummyHead;
while(n--)
{
int val;
cin>>val;
//根据val值构造一个新的节点
ListNode *newNode=new ListNode(val);
//使当前尾节点next指针指向下一个新节点,从而将新节点接入链表
cur ->next=newNode;
//使cur指针指向新创建的节点
cur=cur ->next;
}
}
//定义输出第m个元素的函数
void printList(int n,int m,ListNode *dummyHead)
{
ListNode *cur=dummyHead;
if(m>0&&m<n+1)
{
while(m--)
{
cur=cur ->next;
}
cout<<cur ->val<<endl;
}
else
{
cout<<"Output position out of bounds."<<endl;
}
}
int main()
{
ListNode *dummyHead=new ListNode(0);//定义虚拟头节点
int n,k;
cin >>n>>k;
getList(n,dummyHead);
while(k--)
{
int m;
cin>>m;
printList(n,m,dummyHead);
}
return 0;
}
注意点:刚开始写出的错误代码如下:
错误把cin>>k写到 getList(n,dummyHead)后面,导致测试数据里面的k=5被当成链表数据写进了链表。下次注意,嘻嘻嘻!