Bubble Sort:
#include<iostream>
#include<cstdio>
#include<cstdlib>
using namespace std;
const int size=5;
int a[size]={
5,1,3,2,4};
void buble_sort(){
for(int i=1;i<size;i++){
int flag=1;
for(int j=0;j<=size-i-1;j++){
if(a[j]>a[j+1]){
swap(a[j],a[j+1]);
flag=0;
}
}
if(flag) break;
}
}
int main(){
buble_sort();
for(int i=0;i<size;i++){
cout<<a[i]<<" ";
}
cout<<endl;
return 0;
}
Single list:
#include<iostream>
#include<cstdio>
#include<cstdlib>
using namespace std;
typedef struct LinkList{
int data;
struct LinkList *next;
}L;
L *h=(L*)malloc(sizeof(L));
void init(){
h->next=NULL;
}
void insert(){
int key=-1;
cout<<"输入元素空格隔开,-1表示结束"<<endl;
L *p=(L*)malloc(sizeof(L));
p=h;
cin>>key;
do{
L *n=(L*)malloc(sizeof(L));
n->data=key;
p->next=n;
p=p->next;
p->next=NULL;
cin>>key;
}while(key!=-1);
}
void del_be_index(int index){
L *n=(L*)malloc(sizeof(L));
L *be=(L*)malloc(sizeof(L));
n=h->next;
be=h;
int now=1;
while(n!=NULL){
if(now==index) {
//删除操作
be->next=n->next;
free(n);
return;
}else{
now++;
n=n->next;
be=be->next;
}
}
cout<<"未找到"<<endl;
return;
}
void del_by_key(int key){
L *n=(L*)malloc(sizeof(L));
L *be=(L*)malloc(sizeof(L));
n=h->next;
be=h;
while(n!=NULL){
if(n->data==key){
be->next=n->next;
free(n);
return;
}else{
n=n->next;
be=be->next;
}
}
cout<<"未找到"<<endl;
return;
}
void p(){
L *n=h;
while(n->next!=NULL){
cout<<n->next->data<<endl;
n=n->next;
}
}
int main(){
init();
insert();
p();
del_by_key(6);
p();
del_be_index(1);
p();
return 0;
}