单链表基本操作(二)

得到单链表的长度:(头结点不计算在内)

int length(LNode *L)
{
    int len = 0;
    struct LNode *temp = L->next;
    
    while(temp != NULL){
    	len++;
    	temp = temp->next;
    }
    return len;
}

单链表的删除:删除指定结点并返回删除结点的数据

ElemType deleteLNode(LNode *L,int idx)
{
    int i = 0;
    ElemType ch = '\0';
    struct LNode *pre = L;         /* 前驱结点 */
    struct LNode *cur = L->next;   /* 当前结点 */
    while(cur!=NULL&&i<idx-1){
	pre = cur;
	cur = cur->next;
	i++;
    }
    if(NULL==cur||i>idx-1){
	return -1;
    }
    /*delete*/
    ch = cur->data;
    pre->next = cur->next;
    free(cur);
    return ch;
}

插入一个元素到第idx个结点之前

int insert(LNode *L,int idx,ElemType ch)
{

    int i = 0;
    struct LNode *new_node = NULL;   /* 新结点 */
    struct LNode *cur = L->next;     /* 当前结点 */
    struct LNode *pre = L;           /* 前驱结点 */ 
    while(cur!=NULL&&i<idx-1){
	pre = cur;
	cur = cur->next;
	i++;
    }
    if(NULL==cur||i>idx-1){
	return -1;
    }
    new_node = (LNode *)malloc(sizeof(LNode));
    if(NULL == new_node){  
         return -1;
    }else{
	new_node->data = ch;
	new_node->next = cur;
	pre->next = new_node;
    }
    return OK;
}


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值