链表的操作和动态内存分配

1 动态内存分配

1.1 malloc

//malloc函数动态申请内存,返回类型是申请的同变量类型的指针
//如果申请失败,则返回空指针NULL 
typename* p1=(typename*)malloc(sizeof(typename));
//对应malloc的内存释放
free(p1); 

1.2 new

//new运算符申请动态空间
//如果申请失败,则会启动C++异常机制处理 
typename* p2=new typename; 
//对应new的内存释放
delete(p2); 

2 动态链表

2.1 链表结点

//链表结构体
struct node{
	int data;	//数据域 
	node* next; 
};

2.2 创建链表

//创建链表
node* create(int array[]){
	node *p,*pre,*head;	//pre是前驱结点,head是头结点
	head=new node;	//创建头结点 
	head->next=NULL; 	//头结点不需要数据域,指针域初始化为NULL 
	pre=head;	//记录pre为head 
	for(int i=0;i<5;i++){
		p=new node;			//新建节点
		p->data=array[i];	//赋值给新结点作为数据域 
		p->next=NULL;		//指针域为NULL 
		pre->next=p;		//连上前驱结点的指针域 
		pre=p;				//把p设为下个结点的前驱结点 
	} 
	return head;	//前驱结点 
} 

2.3 查询元素

//在以head为头结点的链表上计数元素x的个数
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;
}

2.4 插入结点

//将x插入以head为头结点的链表的第pos个位置上
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;
}

2.5 删除结点

//删除以head为头结点的链表中所有数据域为x的结点
void del(node* head,int x){
	node* p=head->next;
	node* pre=head;
	while(p!=NULL){
		if(p->data==x){
			printf("YES\n");
			pre->next=p->next;
			delete(p);
			p=pre->next;
		}else{
			pre=p;
			p=p->next;
		}
	}
}

3 静态链表

//静态链表
struct Node{
	typename data;	//数据域
	int next;		//指针域 
}node[size]; 

 

  • 4
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值