动态单链表操作(1)

/*查看链表中是否存在某个节点*/
int localListLookup(local_list_t **list, int id)
{   
    while (*list != NULL) 
    {
        if ((*list)->id == id) 
        {
            return TRUE;
        }
        list = &(*list)->next;
    }

	return FALSE;
}

/*添加新节点*/
int localListAdd(local_list_t **list, int id)
{    

    local_list_t  *v;

    v = (local_list_t *)malloc(sizeof(local_list_t));

    if (v == NULL)
    {
        return FALSE;
    }

    v->id = id;

    v->next = *list;
    *list = v;
    return TRUE;
}

/*删除节点*/
int localListDel(local_list_t **list, int id)
{

    local_list_t     *v;

    while (*list != NULL) 
    {
	if ((*list)->id == id)
        {
	    v = *list;
	    *list = v->next;
	    free(v);
	    return OK;
	}
	
        list = &(*list)->next;
    }
    return OK;
}


int efpListUpdateProcess(int id, char mode)
{
    if (mode == ADD)
    {
        if (localListLookup(&efpInfo.list, id))
        {			
            return ALREADY_EXIST;
        }

       if (localListAdd(&efpInfo.list, id))
        {
            efpInfo.count++;
	    printf("count = %d\r\n",efpInfo.count);
            return OK;
        }   
    }
    else
    if (mode == DELETE)
    {
        if (!localListLookup(&efpInfo.list, id))
        {
            return NOT_EXIST;
        }

        if (localListDel(&efpInfo.list, id))
        {
            efpInfo.count--;
	    printf("count = %d\r\n",efpInfo.count);
            return OK;
        }   
    }

    return ERROR;
}

/*打印链表*/
void print_list()
{
    local_list_t *p;

    p = efpInfo.list;

    while(p != NULL)
    {
	printf("%d  ",p->id);
	p = p->next;
    }	
}



void main()
{
	int id,handle;
	efpInfo.count = 0;
	efpInfo.list = NULL;

	handle =1;
	while(1)
	{
	    print_list();
	    printf("请输入节点ID:");
	    scanf("%d",&id);
	    printf("请输入删除或添加操作,1为添加,0为删除: handle = ");
	    scanf("%d",&handle);

	    efpListUpdateProcess(id,handle);
		
	    print_list();
	    printf("\r\n\n");
		
	    if (id == 255)
	    {
	        break;
	    }
	}	
	
}
<pre name="code" class="cpp">/*.h中数据结构的定义*/
typedef struct local_list_s
{
    int id;
    struct local_list_s *next;    
} local_list_t;  
    
typedef struct
{
    local_list_t *list;
    int count;
} local_info_t;
 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值