跳到正文

个人记录

单链表

#SUSPENDED#约 3 分钟
原文
文章信息与版本

文章信息

收录
2025年12月12日
更新
2025年12月12日
篇幅
约 3 分钟

版本

  1. v1当前

单遍历:

C++
#include<bits/stdc++.h>
using namespace std;
struct N{
	int d;
	N *n;
};
void bl(N *h){
	N *p=new N;
	p=h->n;
	while(p!=NULL){
		cout<<p->d<<" ";
		p=p->n;
	}
}
int main(){
	N *h=new N;
	N *t=h;
	int x;
	while(cin>>x){
		if(x==-1) break;
		N *p=new N;
		p->d=x;
		p->n=NULL;
		t->n=p;
		t=t->n;
	}
	bl(h);
	return 0;
}

单插入:

C++
#include<bits/stdc++.h>
using namespace std;
struct N{
	int d;
	N *n;
};
int find(N *h,int num){
	N *p=new N;
	p=h->n;
	int cnt=1;
	while(p!=NULL){
		if(p->d==num) return cnt;
		p=p->n;
		cnt++;
	}
	return -1;
}
int main(){
	N *h=new N;
	N *t=h;
	int x;
	while(cin>>x){
		if(x==-1) break;
		N *p=new N;
		p->d=x;
		p->n=NULL;
		t->n=p;
		t=t->n;
	}
	int num;
	cin>>num;
	cout<<find(h,num);
	return 0;
}

单查寻:

C++
#include<bits/stdc++.h>
using namespace std;
struct N{
	int d;
	N *n;
};
int find_(N *h,int n){
	N *p=new N;
	p=h->n;
	int cnt=1;
	while(p!=NULL){
		if(p->d==n) return cnt;
		p=p->n;
		cnt++;
	}
	return -1;
}
int main(){
	N *h=new N;
	N *t=h;
	int x;
	while(cin>>x){
		if(x==-1) break;
		N *p=new N;
		p->d=x;
		p->n=NULL;
		t->n=p;
		t=t->n;
	}
	int n;
	cin>>n;
	cout<<find_(h,n);
	return 0;
}

单删除:

C++
#include <bits/stdc++.h>
using namespace std;
struct N{
	int d;
	N *n;
};
void bl(N *h){
	N *p=new N;
	p=h->n;
	while(p!=NULL){
		cout<<p->d<<" ";
		p=p->n;
	}
}
void Delete(N *h,int x){
	N *s=new N;
	s=h->n;
	N *r=h;
	while(s!=NULL){
		if(s->d==x){
			r->n=r->n->n;
			delete s;
			return;
		}
		r=s;
		s=s->n;
	}
}
int main(){
	N *h=new N;
	N *t=h;
	int x,a;
	while(cin>>x){
		if(x==-1) break;
		N *p=new N;
		p->d=x;
		p->n=NULL;
		t->n=p;
		t=p;
	}
	cin>>a;
	Delete(h,a);
	bl(h);
	return 0;
}
原文