这里先说一下我的错误解法吧,提示说是出现段错误,但是确实没找到有什么段错误的地方,所以暂时就先放在这里了,这个是结构体的链表基础用法,尾插入出错之后使用头插法进行修改,发现这里就没有什么问题了
错误解法
#include<iostream>
using namespace std;
struct ListNode{
int data;
ListNode* next;
};
int main(){
int n,x,k;
while(cin>>n){
ListNode *p,*head,*r;
//定义头指针,没有数据
head=new ListNode;
r=head;
for(int i=0;i<n;i++){
cin>>x;
p=new ListNode;
p->data=x;
p->next=NULL;
r->next=p;
r=p;
}
p=head->next;
cin>>k;
k=n-k;
p=head->next;
while(k--){
p=p->next;
}
cout<<p->data<<endl;
}
return 0;
}
//正确解法
#include<iostream>
using namespace std;
struct ListNode{
int data;
ListNode* next;
};
int main(){
int n,x,k;
while(cin>>n){
ListNode *p,*head,*r;
//定义头指针,没有数据
head=new ListNode;
r=head;
for(int i=0;i<n;i++){
cin>>x;
p=new ListNode;
p->data=x;
p->next=NULL;
p->next=head->next;
head->next=p;
}
p=head;
cin>>k;
while(k--){
p=p->next;
}
cout<<p->data<<endl;
}
return 0;
} 
京公网安备 11010502036488号