链表的使用

  • 链表的定义
  • 链表的增删改查
  • 静态链表
定义链表
  1. 定义节点类型
    struct node{
    	int data;
    	node* next;
    }; 
    
  2. 给链表节点分配内存空间
    • malloc C语言中用来申请动态内存的函数:typename* p = (typename*) malloc(sizeof(typename))
      使用结束之后可以通过free() 函数释放内存:free(p)
    • new C++中用来申请动态内存的函数:typename* p = new typename
      使用结束之后可以通过delete()来释放空间:delete(p)
  3. 创建链表
    node* create(int Array[]){
    	node *p,*pre,*head;
    	head = new node;	
    	head->next = NULL;
    	pre = head;
    	for(int i = 0;i<5;i++){
    		p = new node;
    		p->data = Array[i];
    		p->next = NULL;
    		pre->next = p;
    		pre = p;
    	}
    	return head;
    }
    
  4. 查找节点
    int search(node* head,int x){
    	int count = 0;
    	node* L = head->next;
    	while(L!=NULL){
    		if(L->data == x)
    			count++;
    		L = L->next;
    	}
    	return count;
    }
    
  5. 插入节点
    void insert(node* L,int position, int x){
    	node* p = new node;
    	p->data = x;
    	node* pos = L;
    	for(int i=0; i<position-1;i++){
    		pos = pos->next;
    	}
    	p->next = pos->next;
    	pos->next = p;	 
    }
    
  6. 删除节点
    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;
    		}
    		else{
    			p = p->next;
    			pre = pre->next;
    		}
    	} 
    }
    
静态链表

运行时分配内存空间的是动态链表。而提前声明结构体数组来表示的叫做静态链表
静态链表的定义

struct Node{
	typename data;
	int next;
}node[size];
  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值