链表基本操作--c

创建--打印--转置--释放

#include<stdio.h>
#include<stdlib.h>  //exit()
#include<string.h> //字符串头文件
struct list{
    int val;
    struct list* next;
};

struct double_list{
    int val;
    struct list* next;
    struct list* prev;
};

struct list* creat_list(int size);
int print_list(struct list* head);
int free_list(struct list* head);
struct list* cove_list(struct list* head);


int main()
{	
    struct list* head = NULL;

    head = creat_list(3);  
    print_list(head);
    
    head = cove_list(head);
    printf("after conv\n");
    print_list(head);   

    free_list(head);    
    printf("%s[%d] version : 07\n", __func__, __LINE__);

	return 0;
}

struct list* creat_list(int size)
{
	int index = 0;
    struct list* head = NULL;
    struct list* cur = NULL;
    struct list* prev = NULL;
	
	for(index=0; index<size; index++)
	{
		/* 分配内存 */
		cur = (struct list*)malloc(sizeof(struct list));
    	if(NULL == cur) 
        	printf("malloc fail\n");

		/* 串联节点 */
		if(NULL == head)
			head = cur;
		else
			prev->next = cur;

		/* 赋值 */
		cur->val = index;
		cur->next = NULL;
		prev = cur;		
	}
    
    return head;
}

int print_list(struct list* head)
{
    int index = 0;
    struct list* cur = NULL;
    
    if(NULL == head)
        printf("%s(%d) input is null\n", __func__, __LINE__);
    
	cur = head;
	while(NULL != cur)
	{
		printf("index[%d]: %d\n", index, cur->val);
		cur = cur->next;
        index++;
	}
    
    return 0;
}

int free_list(struct list* head)
{
    int index = 0;
    struct list* cur;
    
    while(NULL != head)
    {
        cur = head;
        head = head->next;
        free(cur); 
        printf("free %d\n", index);
        index++; 
    }
    return 0;
}

/*转置处理*/
struct list* cove_list(struct list* head)
{
    struct list* next = NULL;
    struct list* prev = NULL;
    struct list* cur = NULL;
    
    if(NULL == head)
        printf("%s(%d) input is null\n", __func__, __LINE__);
    
    cur = head;
    prev = cur->next;
    cur->next = next;
    
    while(prev != NULL)
    {
        next = cur;
        cur = prev;
        prev = prev->next;
        
        cur->next = next;        
    }
    head = cur;
    
    return head;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值