一种采用指针的指针的方式的建立链表的方法

最近在看posix多线程程序设计,第四章中流水线的例子中,建立链表的方法比较独特,之前没看到过,还是自己代码写得少。例子如下代码

int pipe_index;
stage_t **link = &pipe->head, *new_stage, *stage;
int status;

    status = pthread_mutex_init (&pipe->mutex, NULL);
    if (status != 0)
        err_abort (status, "Init pipe mutex");
    pipe->stages = stages;
    pipe->active = 0;

    for (pipe_index = 0; pipe_index <= stages; pipe_index++) {
        new_stage = (stage_t*)malloc (sizeof (stage_t));
        if (new_stage == NULL)
            errno_abort ("Allocate stage");
        status = pthread_mutex_init (&new_stage->mutex, NULL);
        if (status != 0)
            err_abort (status, "Init stage mutex");
        status = pthread_cond_init (&new_stage->avail, NULL);
        if (status != 0)
            err_abort (status, "Init avail condition");
        status = pthread_cond_init (&new_stage->ready, NULL);
        if (status != 0)
            err_abort (status, "Init ready condition");
        new_stage->data_ready = 0;
        *link = new_stage;
        link = &new_stage->next;
    }

    *link = (stage_t*)NULL;     /* Terminate list */
    pipe->tail = new_stage;     /* Record the tail */

这里运用指针的指针来创建单链表。
我的理解是:首先link是指向*link的,循环开始之前,link指向*link,*link指向head所指向的内存单元,第一次循环执行完*link  = new_stage;此时*link指向了new_stage所指内存单元,执行link = &new_stage->next之后,link地址内存单元的内容是new_stage->next,即link指向了内存单元内容为:new_stage->next,通过对*link的修改也会造成new_stage->next被修改,所以下次循环之后*link指向了一个新的内存单元,也会使得new_stage->next指向该单元,如此单链表便可以连接起来。

测试程序如下:

#include <stdio.h>
#include <stdlib.h>

typedef struct stage_tag
{
	int              data_ready;
	long             data;
	struct stage_tag *next;
}stage_t;

stage_t *list_create(int stages)
{
	int index;
	stage_t *head = NULL, *tail = NULL;
	stage_t **link = &head, *new_stage, *stage;

	for (index = 0; index < stages; index++)
	{
		new_stage = (stage_t*) malloc (sizeof(stage_t));
		if (new_stage == NULL)
		{
			printf("new_stage is null\n");
			return -1;
		}
		new_stage->data_ready = 0;
		new_stage->data = index;
		*link = new_stage;
		link = &new_stage->next;
	}
	*link = (stage_t*)NULL;
	tail = new_stage;
	return head;
}

int main()
{
	stage_t *head = list_create(4);
	while(head)
	{
		printf("data:%d\n", head->data);
		head = head->next;
	}
	return 0;
}

结果如下:

data:0
data:1
data:2
data:3






评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值