c/c++的双向链表基本知识(创建,输出,排序,合并)超详解

先复习下数组的排序:

1定长数组排序(选择和冒泡)
#include<iostream>
using namespace std;
void selectpx(){
	int i,j,a[10];
	for(i=0;i<10;i++){
		cout<<"输入a["<<i<<"]的数"<<endl ;
		cin>>a[i];
	}
	for(i=0;i<9;i++){
		for(j=i+1;j<10;j++){
			int temp;
			if(a[i]>a[j]){
				temp=a[i];
				a[i]=a[j];
				a[j]=temp;
			}
		}
	}
	cout<<"输出数组:"<<endl;
	for(i=0;i<10;i++){
		cout<<a[i]<<endl;
	}
}
void maobaopx(){
	int i,j,a[10];
		for(i=0;i<10;i++){
		cout<<"输入a["<<i<<"]的数"<<endl ;
		cin>>a[i];
	}
	for(i=0;i<9;i++){
		for(j=0;j<10-i-1;j++){
			int temp;
			if(a[j]>a[j+1]){
				temp=a[j];
				a[j]=a[j+1];
				a[j+1]=temp; 
			}
		}
	}
		cout<<"输出数组:"<<endl;
	for(i=0;i<10;i++){
		cout<<a[i]<<endl;
	}
}
int main(){
	selectpx();
	//maobaopx();
	return 0;
}

 运行截图:

链表的各功能实现:

#include<iostream>
 using namespace std;
 //***定义节点****
 typedef struct listpoint
{
    int age;
    string name;
    listpoint *next;
    listpoint *last;
}listpoint;//定义 listpoint类型 
    listpoint * createlist(){//创建链表函数 
    	int n;
    	listpoint *head=NULL,*end=NULL,*point=NULL;
    	cout<<"创建链表节点数"<<endl;
		cin>>n;
		if(n<=0){//判断输入节点数是否合理 
			cout<<"非法"<<endl;
			return head;//异常就退出 
		} 
		else{
			head=new listpoint;//实例化一个点,这里用mallco ()有时候会出现一些错误,new()的包容性更好,缺点是->后面的变量需要自己手打,系统检测不出来。 
			end=head;
			for(int i=0;i<n;i++){
				point=new listpoint;
				cout<<"输入姓名"<<endl;
				cin>>point->name;
				cout<<"输入年龄"<<endl;
				cin>>point->age;
				end->next=point;//尾插法的经典行为 
				end=point;
			}
			head->last=NULL;
			end->next=NULL;
		}
		return head;
	}
void allcout(listpoint *head){//全输出链表里的信息 
	listpoint *point=head;
	while((	point=point->next)!=NULL){
	cout<<"姓名:"<<point->name<<endl;
	cout<<"年龄:"<<point->age<<endl;
}
}
void listmaopao(listpoint *head){
	listpoint *point=head,*L,*p,*q;
	int i,j,count=0;
	while((point=point->next)!=NULL){//算出链表有几个节点,不包括空的头节点 
		count++;
	}
	//cout<<count<<endl;
	for(i=0;i<count-1;i++){//冒泡排序的外循环 
    	L=head,p=head->next,q=p->next;//每一次内循环需要恢复到最开始,除了上一次内循环得出的最大的那一个。 
    	L->last=NULL,p->last=head,q->last=p;
		for(j=0;j<count-1-i;j++){//外循环 
			if(p->age>q->age){
				p->next=q->next;
				p->last=q;
				q->next=p;
				q->last=L; 
				L->next=q;//节点设置 
			}
			L->last=L;
			L=L->next;
			p->last=L;
			p=L->next;
			q->last=p;
			q=p->next;//当if(){}里面的语句使得a[j]<a[j+1],指针全部向下移一位 ,并且是按开始时的p节点在q节点上一位,这是因为要考略下一次if()里面的语句调用的正确1性。 
		}
	}
}
void listhp1(listpoint *head,listpoint *head1){//链表合并,并且默认使用转来的第一个地址作为合并后的链表的头指针· 
	listpoint *point=head;
	listpoint *point1=head1;
	
	while(1){
		if(point->next!=NULL){
			point=point->next;
		}
		else{
			point->next=head1->next;
			break;
		}
	}
	
}

	int main(){
		listpoint *head,*head1;
		head=createlist();
		head1=createlist();//创建两个链表 
		listhp1(head,head1);//合并链表,并返回头指针 
		listmaopao(head);//排序合并链表。 
		allcout(head);//全输出 
		return 0;
	}

运行截图:

 本学渣原创。

猜你喜欢

转载自blog.csdn.net/m0_53394907/article/details/123946794