版权声明:原创文章,转载请注明出处 https://blog.csdn.net/hza419763578/article/details/88534013
自己实现单链表 指针实现
create search insert del
#include<iostream>
using namespace std;
struct node
{
//数据域和指针域即可
int data;
node* next;
};
//创建一个单向链表 根据数组来初始化相应结点
node* create(int Array[],int n){//n是数组长度
node *p,*pre,*head;//p当前结点(缓存区) head头结点 pre当前结点的前驱结点
head=new node;//为头结点分配存储空间 不用c语言的malloc了,麻烦 c++ "new 数据类型"多好
head->next=NULL;//初始只有一个头结点, 当然头结点也没有数据域
pre=head;//下一个待创建结点的前驱 head已经分配了内存空间 pre指向同一块空间
for(int i=0;i<5;i++){
p=new node;
p->data=Array[i];
p->next=NULL;//万一是尾结点呢,最好指向NULL
pre->next=p;
pre=p;
}
return head;//返回头结点
}
//查找元素 返回给定元素在链表中出现的次数 0表示未找到
int search(node* head,int x){
int count=0;
node* p=head->next;//最好不要直接动头指针
while(p!=NULL){
if(p->data==x) count++;
p=p->next;
}
return count;
}
//插入操作
//将x插入head为头结点的链表的第pos个位置上 第pos个结点的左边(head->next为第一个结点)
void insert(node* head,int pos,int x){
node* p=head;
for(int i=0;i<pos-1;i++){//找到待插入结点的前一个结点
p=p->next;
}
//插入
node* q=new node;
q->data=x;
q->next=p->next;
p->next=q;
}
//删除元素
//删除链表head中所有数据域为x的结点
void del(node* head,int x){
node* pre=head;//加一个前驱好写一点
node* p=head->next;
while(p!=NULL){
if(p->data==x){
pre->next=p->next;
delete(p);
p=pre->next;//p始终要更新 释放的是p指向的内存单元 不是指针变量p
}else{
pre=p;
p=p->next;
}
}
}
void printL(node* L){
L=L->next;//头结点没有数据域 必须重第一个结点开始
while(L!=NULL){
cout<<L->data<<" ";
L=L->next;
}
cout<<endl;
}
int main(){
const int N=5;
int Array[N]={1,7,2,3,1};
node* L=create(Array,N);
cout<<"测试创建:\n";
printL(L);
cout<<"\n测试查找:\n";
int a[3]={10,7,1};
for(int i=0;i<3;i++){
cout<<a[i]<<":"<<search(L,a[i])<<endl;
}
cout<<"\n测试插入:\n";
insert(L,3,1);
printL(L);
insert(L,4,-4);
printL(L);
insert(L,5,-5);
printL(L);
cout<<"\n测试删除:\n";
del(L,-4);
printL(L);
del(L,-5);
printL(L);
del(L,1);
printL(L);
return 0;
}
静态链表
struct Node{
int date;
int next;//指针域 就是下一个结点的下标
}node[size];
#include<iostream>
using namespace std;
struct Node
{
int data;
int next;
// string desc;
}node[100000];
//地址address 对应数值Array 按顺序连接
int create(int Array[],int address[],int n){
for(int i=0;i<n;i++){
node[address[i]].data=Array[i];
if(i+1<n)
node[address[i]].next=address[i+1];
else node[address[i]].next=-1;
}
return address[0];
}
void printL(int h,const Node* node){
for(int p=h;p!=-1;p=node[p].next){
cout<<node[p].data<<" ";
}
cout<<endl;
}
int main(){
int Array[10]={5,34,56,1,2,4,-9,-67,9,10};
int address[10]={1001,1009,1045,1063,1078,1000,1002,1065,1089,2000};
int h=create(Array,address,10);
printL(h,node);
return 0;
}
本节练习:
https://blog.csdn.net/hza419763578/article/details/88535976