线性表——指针实现

本文展示了使用C++通过指针实现线性表的基本操作,包括在指定位置插入元素、删除元素、查找元素以及找到线性表的末尾。代码中定义了结构体node,并提供了相应的函数如Insert、Delete、Locate和End等,用于线性表的管理。在main函数中,创建了一个线性表并进行了插入、打印、删除和查找等操作,展示了这些函数的实际应用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#include<iostream>
#include<cstring>
#include<cstdio>
#include<cmath>
#include<algorithm>
using namespace std;
#define ms(a) memset(a,0,sizeof(a))
typedef int Elementtype;

struct node{  
    Elementtype element;  
    node* next=NULL;  
};  
  
typedef node* LIST;  
typedef node* position; 

/*	End
	返回最后一个元素的位置
*/ 
position End(LIST L){
	position p=L;
	while(p->next!=NULL){
		p=p->next;
	}
	return p;
}

/*	Insert
	在 p 处下一个位置插入元素 x 
*/ 
void Insert(Elementtype x,position p){
	position tem;
	tem=p->next;
	p->next=new node;
	p->next->element=x;
	p->next->next=tem;
} 

/*	Delete
	删除位于 p 后面一个位置的元素 
*/ 
void Delete(position p){
	position t;
	if(p->next!=NULL){
		t=p->next;
		p->next=t->next;
		delete t;
	}
}

/*	Locate
	返回  L 中 x 的位置
*/ 
position Locate(Elementtype x,LIST L){
	position p=L;
	if(p->next!=NULL){
		if(p->next->element==x){
			return p;
		}
		else{
			p=p->next;
		}
	}
	return p;
}

/*	Makenull
	将 L 置空 
*/ 
position Makenull(LIST &L){
	L=new node;
	L->next=NULL;
	return L;
}

void Print(LIST L){
	position p=L->next;
	if(p==NULL){
		cout<<"List is empty."<<endl;
	}
	else{
		while(p!=NULL){
			cout<<p->element<<" ";
			p=p->next;
		}
		cout<<endl;
	}	
}

int main(){
	LIST L=new node;
	Insert(1,L);
	Insert(2,L);
	Insert(3,L);
	Insert(4,L);
	Print(L);
	Delete(L);
	Print(L);
	cout<<Locate(2,L)<<endl;
	cout<<End(L);
	return 0;
} 



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值