王老师 结构体 第二讲

1.动态申请内存块,原型:

void * malloc(int  x);

功能:申请大小为x的内存块,返回所分配内存起始地址或空指针.该空间是在堆中分配的.

释放内存:

void free(void *p);

p所指的内存区域一定是由函数malloc分配的.

2.定义新类型名:

typedef 复合说明项

其好处在于:能为c语言中没有名字的数据类型定义一个名字.

例如:

typedef int T;              T a, b[10];

typedef int *IP;           IP p, *q, r[10]; <==> int *p, **q, *r[10];

typedef int A[10];        A x, y[5], *p;    <==> int x[10], y[5][10], (*p)[10];

typedef int F(int);        F *f;                 <==> int (*f)(int);

c语言中唯一的一个先使用后定义的情况:

typedef struct node NODE;

struct node {
 int info;
 NODE *next;
};

3.链表插入(按值从小到大排列)

示例程序代码如下:

#include "stdio.h"
#include "malloc.h"

typedef struct node NODE;

struct node {
 int info;
 NODE *next;
};

//链表插入,不正确.
void insert(NODE *h, int x){
 NODE *p = h, *q, *r;
 while(p != NULL && p->info < x){
  q = p;
  p = p->next;
 }
 //生成一个新节点
 r = (NODE *)malloc(sizeof(NODE));
 r->info = x;
 if(h != p){
  q->next = r;
  r->next = p;
 }else{
  r->next = h;
  h = r;
 }
}

//链表插入,法一.
void insert1(NODE **h, int x){
 NODE *p = *h, *q, *r;
 while(p != NULL && p->info < x){
  q = p;
  p = p->next;
 }
 //生成一个新节点
 r = (NODE *)malloc(sizeof(NODE));
 r->info = x;
 if(*h != p){
  q->next = r;
  r->next = p;
 }else{
  r->next = *h;
  *h = r;
 }
}

//链表插入,法二.
NODE * insert2(NODE *h, int x){
 NODE *p = h, *q, *r;
 while(p != NULL && p->info < x){
  q = p;
  p = p->next;
 }
 //生成一个新节点
 r = (NODE *)malloc(sizeof(NODE));
 r->info = x;
 if(h != p){
  q->next = r;
  r->next = p;
 }else{
  r->next = h;
  h = r;
 }
 return h;
}

//打印链表
void print(NODE *h){
 while(h){
  printf("%d/t", h->info);
  h = h->next;
 }
}

void main()
{
 NODE *head = NULL;
 //insert(head, 10);
 //insert(head, 20);
 //insert(head, 15);
 //什么也没打印,具体分析略,应如何改?
 //print(head);
 
 //法一,传指针,改变head值
 //insert1(&head, 10);
 //insert1(&head, 20);
 //insert1(&head, 15);
 //print(head);
 
 //法二,返回头节点
 head = insert2(head, 10);
 head = insert2(head, 20);
 head = insert2(head, 15);
 print(head);
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值