c语言实现链表

c语言的动态内存管理函数实现动态内存管理;

1、malloc() 函数

void *malloc(unsigned int size);

分配一块长度为size字节的连续空间,并将该空间的首地址作为函数的返回值。

2、calloc()函数

void *calloc(unsigned int n, unsigned  int size);

分配一块长度为n*size字节的连续空间,并将该空间的首地址作为函数的返回值。

3、free()函数

void free(void *block);

释放分配给指针变量block的动态空间。

代码:

#include <stdio.h>
#include <stdlib.h>
#define N 4 

struct node{
	int data;
	struct node *next;
}; 

int main(int argc, char *argv[]) {
	struct node *create_node(void);
	struct node *create_list(int);
	void out_list(struct node *);
	struct node *head=NULL;
	head=create_list(N);
	out_list(head);
	return 0;
}

//创建节点 
struct node *create_node(void){
	struct node *p;
	p=(struct node *)calloc(1,sizeof(struct node));
	scanf("%d",&(p->data));
	p->next=NULL;
	return p;
}

//创建链表 
struct node *create_list(int n){
	struct node *new,*head,*p;
	int i;
	if(n>=1){
	new=create_node();
	head=new;
	p=new;	/*p指向链表最后一个节点*/
	}
	for(i=2;i<=n;i++){
		new=create_node();
		p->next=new;
		p=new;
	}
	if(n>=1){
		return head;
	}
	else{
		return NULL;
	}
}

//输出链表 
void out_list(struct node *head){
	struct node *p;
	if(head!=NULL){
		p=head;
		while(p!=NULL){
			printf("%d",p->data);
			p=p->next;
		}
	}
} 

//删除节点p 
struct node *delete(struct node *head,struct node *P){
	struct node *q;
	if(p==NULL){
		return head;
	}
	if(p==head){
		head=head->next;
	}
	else{
		q=head;
		while(q->next!=p){
			q=q->next;
		}
		q->next=p->next;
	}
	free(p);
	return head;
}

//查找data=x的节点 
struct node *find(struct node *head,int x){
	struct node *q;
	q=head;
	while(p!=NULL&&p->data!=x){
		p=p->next;
	}
	if(p==NULL){
		return NULL;
	}
	else{
		return p;
	}
} 

注意:C语言中,%c前面的空格就是用来屏蔽空白符(空格、换行符、制表符的。对于scanf()而言,%c是个较为特殊的说明符。 %c前没空格,scanf()将读取标准输入流中的第一个字符,%c前有空格,scanf()则读取标准输入流中第一个非空白字符。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值