|
|
#2
lengji222011-11-20 21:15
#include<iostream>
#include<stdlib.h> using namespace std; class LinkNode{ public: int data; LinkNode *link; LinkNode(int x){data = x;} LinkNode(){} }; class List{ private: LinkNode *first; public: bool Insert(int i,int x); //插入一个节点 void inputRear(); //建立链表 void output(); // 输出 List(){first = new LinkNode;} virtual ~List(){ if (first !=NULL) { LinkNode *cur = first->link; delete first; first = cur; } } }; bool List::Insert(int i,int x){ if(first==NULL || i==0){ //表头 LinkNode *newNode=new LinkNode(x); if(newNode==NULL){cout<<"No\n";exit(1);} newNode->link=first;first=newNode; } else { LinkNode *current=first; for(int k=1;k<i;k++){ if(current==NULL) break; else current=current->link; } if(current==NULL && first!=NULL){cout<<"No\n";return false;} else{ LinkNode *newNode=new LinkNode(x); if(newNode==NULL){cout<<"No\n";exit(1);} newNode->link=current->link; current->link=newNode; } } return true; }; void List::inputRear(){ LinkNode *last; int val; //LinkNode *newNode=new LinkNode; //创建一个新节点 last = first; //if(first==NULL){cout <<"NO";exit(1);} cout<<"请输入链表数据:"; cin>>val; while(val!='\n'){ LinkNode*newNode=new LinkNode(val); last->link=newNode; last=newNode; cout<<"请输入链表数据:"; cin>>val; } }; void List::output(){ LinkNode *current1=first->link; while(current1!=NULL){ cout<<current1->data<<endl; current1=current1->link; } }; int main(){ List A; A.inputRear(); A.output(); A.Insert(3, 5); A.output(); system("pause"); return 0; } |
#include<iostream>
#include<stdlib.h>
using namespace std;
class LinkNode{
public:
int data;
LinkNode *link;
};
class List:public LinkNode{
private:
LinkNode *first;
public:
bool Insert(int i,int& x); //插入一个节点
void inputRear(); //建立链表
void output(); // 输出
};
bool List::Insert(int i,int& x){
if(first==NULL || i==0){ //表头
LinkNode *newNode=new LinkNode(x);
if(newNode==NULL){cout<<"No\n";exit(1);}
newNode->link=first;first=newNode;
}
else {
LinkNode *current=first;
for(int k=1;k<i;k++){
if(current==NULL) break;
else current=current->link;
}
if(newnode==NULL && first!=NULL){cout<<"No\n";return false;}
else{
LinkNode *newNode=new LinkNode(x);
if(newNode==NULL){cout<<"No\n";exit(1);}
newNode->link=current->link;
current->link=newNode;
}
}
return true;
};
void List::inputRear(){
LinkNode *last;
int val;
LinNode *newNode=new LinkNode(x); //创建一个新节点
first=last=newNode;
if(first==NULL){cout <<"NO";exit(1);}
cin>>val;
while(val!=END){
LinkNode*newNode=new LinkNode(val);
last->link=newNode;
last=newNode;
cin>>val;
}
};
void List::output(){
LinkNode *current1=first->link;
while(current1!=NULL){
cout<<current1->data<<endl;
current1=current1->link;
}
};
int main(){
List A;
A.intputRear();
A.output();
A.Insert(3,5);
A.output();
system("pause");
return 0;
}
PS:以前基础不好,但真心想学习,求指教,谢谢哈...
[ 本帖最后由 小灰i小白 于 2011-11-19 17:19 编辑 ]