这节课复习数据结构。
链表简单来说就是首为0,尾为空(NULL)。
用链表可以进行简单的快速排序(题目)
切记:用链表做会超时!!!(链表时间复杂度O(n方))
#include <bits/stdc++.h>
using namespace std;
const int maxn=100000+10;
int n,m,k;
struct node{
int w,next;
}a[maxn];
int len;
void insert(int s,int k){
int u=s;
while(a[u].next && k>a[a[u].next].w)
u=a[u].next;
a[++len].w=k;
a[len].next=a[u].next;
a[u].next=len;
}
int main(){
scanf("%d",&n);
for(int i=1;i<=n;i++){
scanf("%d",&k);
insert(0,k);
}
int u=a[0].next;
while(a[u].next!=0){
printf("%d ",a[u].w);
u=a[u].next;
}
printf("%d\n",a[u].w);
return 0;
}
扩展:将排好序的这一串链表中插入一个数。
思路就是这样的:发现要插入的位置后,将这个数的前一个数指向它,再将它指向后一个数。
代码略。
扩展再扩展:将排好序的这一串链表中删除一个数。
代码:
#include <bits/stdc++.h>
using namespace std;
const int maxn=100000+10;
int n,m,k;
struct node{
int w,next;
}a[maxn];
int len;
void insert(int s,int k){
int u=s;
while(a[u].next && k>a[a[u].next].w)
u=a[u].next;
a[++len].w=k;
a[len].next=a[u].next;
a[u].next=len;
}
int main(){
scanf("%d",&n);
for(int i=1;i<=n;i++){
scanf("%d",&k);
insert(0,k);
}
int u=a[0].next;
while(a[u].next!=0){
printf("%d ",a[u].w);
u=a[u].next;
}
printf("%d\n",a[u].w);
scanf("%d",&k);
u=0;
while(a[u].next&&a[a[u].next].w!=k)
u=a[u].next;
if(a[u].next==0){
printf("404 NOT FOUND");
return 0;
}
else
a[u].next=a[a[u].next].next;
u=a[0].next;
while(a[u].next!=0){
printf("%d ",a[u].w);
u=a[u].next;
}
printf("%d",a[u].w);
return 0;
}
用指针实现(未输出):
#include <bits/stdc++.h>
using namespace std;
int n,k;
struct node{
int w;
node *next;
node(){
w=0;
next=NULL;
}
};
int main(){
node *h=new node();
scanf("%d",&n);
for(int i=1;i<=n;i++){
scanf("%d",&k);
node *q=new node();
q->w=k;
node *p=h;
while(p->next!=NULL&&k>p->next->w)
p=p->next;
}
node *p=h->next;
while(p!=NULL){
printf("%d ",p->w);
p=p->next;
}
scanf("%d",&k);
p=h;
while(p->next!=NULL&&p->next->w!=k)
p=p->next;
if(p->next==NULL){
printf("404 NOT FOUND");
return 0;
}
else{
node *q=p->next;
p->next=p->next->next;
delete(q);
}
return 0;
}