求改
这段代码有什么问题?为什么出现报错的情况?错在哪了?
求给出改后源码
具体想法:
每个元素的指针指向下一个元素,然后通过 l 指针依次访问
#include<bits/stdc++.h>
using namespace std;
struct L{
int data;//数据域
int *p;//指针域
}a[1001];
int *head;
int *l;
int main() {
for(int i=1;i<=10000;i++){
a[i].data=i+1;
}
head=&a[0].data;
l=head;
for(int i=1;i<=1000;i++){
a[i].p=&a[i+1].data;
}
for(int i=1;i<=9;i++){
l++;
cout<<*l<<endl;
}
return 0;
}
数组越界
不能这样写的,开了数组就要用静态链表,但同时你又用指针。而且前一个元素指向下一个元素的值域,相当于输出i+1的data。
建议养成习惯,要么写静态链表,要么写动态链表。
像这样:动态链表:
#include<iostream>
#include<cstdio>
#include<algorithm>
using namespace std;
struct Node{
int data;
Node *next;
}*head=NULL;
void create_list(int n){
Node *node=NULL;
for(int i=1;i<=n;++i){
node=new Node;
cin>>node->data;
node->next=head;
head=node;
}
}
inline Node *search(Node *p,int x){
if(head==NULL)return NULL;
if(head->data>x)return NULL;
while(p->next!=NULL&&p->next->data<x)p=p->next;
return p;
}
inline void insert(int x){//链表的在线插入排序
Node *node=new Node;
node->data=x;
Node *p=search(head,x);
if(p==NULL){
node->next=head;
head=node;
}else{
node->next=p->next;
p->next=node;
}
}
inline void print(Node *p){
while(p!=NULL){
printf("%d ",p->data);
p=p->next;
}
printf("\n");
}
int main(){
int n,x;
cin>>n;
create_list(n);
print(head);
}