跳到正文

算法·理论

链表

佩露薇利约 3 分钟
原文
文章信息与版本

文章信息

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

版本

  1. v1当前

认识链表

链表头插法(指针)

C++
#include<bits/stdc++.h>
using namespace std;
struct Node{
	int data;
	Node *next;
};
Node *head;
void init(){
	head=new Node();
	head->next=NULL;
}
void insert(int x){
	Node *temp=new Node();
	temp->data=x;
	temp->next=head->next;
	head->next=temp;
}
void print(){
	Node *temp=head->next;
	while(temp!=NULL){
		cout<<temp->data<<' ';
		temp=temp->next;
	}
	cout<<'\n';
}
int n,x;
int main(){
	init();
	cin>>n;
	for(int i=0;i<n;i++){
		cin>>x;
		insert(x);
		print();
	}
	return 0;
}

链表尾插法(指针)

C++
#include<bits/stdc++.h>
using namespace std;
struct Node{
	int data;
	Node *next;
};
Node *head;
Node *tail;
void init(){
	head=new Node();
	tail=new Node();
	head->next=NULL;
	tail=head;
}
void insert(int x){
	Node *temp=new Node();
	temp->data=x;
	temp->next=NULL;
	tail->next=temp;
	tail=temp;
}
void print(){
	Node *temp=head->next;
	while(temp!=NULL){
		cout<<temp->data<<' ';
		temp=temp->next;
	}
	cout<<'\n';
}
int n,x;
int main(){
	init();
	cin>>n;
	for(int i=0;i<n;i++){
		cin>>x;
		insert(x);
		print();
	}
	return 0;
}

链表头插法(数组)

C++
#include<bits/stdc++.h>
using namespace std;
const int MAX=1e5+1;
int n,x,idx,head=-1,temp[MAX],next[MAX];
void insert(int x){
	temp[idx]=x;
	next[idx]=head;
	head=idx;
	idx++;
}
void print(){
	for(int i=head;i!=-1;i=next[i])
		cout<<temp[i]<<' ';
	cout<<'\n';
}
int main(){
	cin>>n;
	for(int i=0;i<n;i++){
		cin>>x;
		insert(x);
		print();
	}
	return 0;
}
原文