c++小问题,编程题

来源:百度知道 编辑:UC知道 时间:2024/07/08 07:58:03
生成一个单链表,表头指针为h,节点的KEY分别为1到N,N为用户任意输入的一个整数。
NODE *h;
struct NODE {
int KEY;
NODE * next;
}

#include "iostream.h"
typedef struct NODE {
int KEY;
NODE * next;
}NODE;
NODE *h;
NODE* createnode(int n){
if(n==0) return NULL;
NODE* p,*q;
h=p=new NODE;
p->KEY=1;
p->next=NULL;
for(int i=2;i<=n;i++){
q=p;
p=new NODE;
p->next=NULL;
p->KEY=i;
q->next=p;
}
return h;
}
void main(){
int n;NODE *p,*q;
cout<<"请输入n:"<<endl;
cin>>n;
p=createnode(n);
while(p){cout<<p->KEY;p=p->next;}
p=h;
while(p){q=p->next;delete(p);p=q;}
}