c++實現動態數組

#include<iostream>
using namespace std;
struct ListNode{
	int val;
	ListNode *next;
};
ListNode* greate(){
	ListNode *head=new ListNode;
	head=NULL;
	ListNode *p=head;
	cout<<"please enter student number:";
	int n;
	cin>>n;
	for(int i=0;i<n;i++){
		p=new ListNode;
		p->val=i;
		p->next=head;
		head=p;
	}
	return head;
}
void prin(ListNode* head){
	ListNode *p=head;
	cout<<endl;
	while(p!=NULL){
		cout<<p->val<<endl;
		p=p->next;
	}
}
void insert(ListNode* head,int n){
	ListNode *sert,*nex,*p;
	sert=new ListNode; 
	sert->val=2;
	p=head;
	while(p->val!=n)
	p=p->next; //插入到n後面
	
	nex=p->next;
	p->next=sert;
	sert->next=nex;
}
void deleter(ListNode* head,int n){
	ListNode *out=new ListNode;
	ListNode *p;
	
	p=head;
	while(p->val!=n){
		out=p;
		p=p->next;
	}
	out->next=p->next;
}
int main(){
	ListNode *h1;
	h1=greate();
	prin(h1);
	insert(h1,1);
	prin(h1);
	deleter(h1,0);
	prin(h1);
	return 0;
}

另一個寫法:

#include<iostream>
using namespace std;
struct ListNode{
	int val;
	ListNode *next;
	ListNode(int x) : val(x), next(NULL) {}
};
int num=0;
ListNode* greate(){
	ListNode *head;
	ListNode *p;
	cout<<"please enter student number:";
	int n;
	cin>>n;
	for(int i=0;i<n;i++){
		if(num==0){
			head = new ListNode(i);
		}else{
			p=new ListNode(i);
			p->next=head;
			head=p;
		}
		num++;
	}
	return head;
}
void prin(ListNode* head){
	ListNode *p=head;
	cout<<endl;
	while(p!=NULL){
		cout<<p->val<<endl;
		p=p->next;
	}
}
void insert(ListNode* head,int n){
	ListNode *sert,*nex,*p;
	sert=new ListNode(2);
	p=head;
	while(p->val!=n)
	p=p->next; //插入到n後面
	
	nex=p->next;
	p->next=sert;
	sert->next=nex;
}
void deleter(ListNode* head,int n){
	ListNode *out=new ListNode(NULL);
	ListNode *p;
	
	p=head;
	while(p->val!=n){
		out=p;
		p=p->next;
	}
	out->next=p->next;
}
int main(){
	ListNode *h1;
	h1=greate();
	prin(h1);
	insert(h1,1);
	prin(h1);
	deleter(h1,0);
	prin(h1);
	return 0;
}

可算把這東西整明白一點了!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章