初学链表,时间过长,有什么解决办法吗
查看原帖
初学链表,时间过长,有什么解决办法吗
1168912
Dailyk楼主2023/11/20 16:40
using namespace std;

#include<iostream>



struct node{

  long long data;

  node* next;

  node(long x):data(x),next(nullptr){}

};



node* head;



void insert(long x){//在末端插入

  node* temp=new node(x);

  node* temp1;

  temp1=head;

   if(head!=nullptr){

    while(temp1->next!=nullptr){

      temp1=temp1->next;

    }

   temp1->next=temp;

   }

   else{

    head=temp;

   }

   //free(temp1);

}



void print(long m){

  node* temp;

  temp=head;

  if(head!=nullptr){

    for(long i=0;i<m-1;i++){

    temp=temp->next;

    }

  }

   

  cout<<temp->data<<endl;

}



int main(){

  long n,m;

  cin>>n>>m;

  for(int i=0;i<n;i++){

    long x;

    cin>>x;

    insert(x);

  }

  for(int i=0;i<m;i++){

   long t;

    cin>>t;

   print(t);

  }

  

  return 0;

}
2023/11/20 16:40
加载中...