链表 2018-11-25

这节课复习数据结构。
链表简单来说就是首为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;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值