C语言删除链表中的结点

1.删除与指定结点相同的第一个结点
测试用例
Input: 1 2 3 2 4 5 2
Output:1 3 2 4 5 2
使用break来终止循环

struct node *DeleteNode(struct node *L, int e)
{    
    struct node *p=L->next,*q=L;
    if (L==NULL)          
    { 
        printf("链表为空\n");
        return L;
    }
    while(p!=NULL)
    {
        if(p->data==e)
        {
            q->next=p->next;
            free(p);
            p=q->next;
            break;//break终止循环
        }
        else 
        {
            p=p->next;
            q=q->next;
        }

    }
    return L;     
}

不用break

struct node *DeleteNode(struct node *L, int e)
{    
    struct node *p=L->next, *q = head;
    if (L==NULL)          
    {
        printf("链表为空\n");
        return L;
    }
    while(e!=p->data&&p!=NULL)
    {     
        q=p;
        p=p->next;
    }
    if (e==p->data) 
    {       
        q->next=p->next;            
        free(p);              
    }
    else                         
        printf("没有找到待删除结点\n"); 
    return L;         
}

2.删除与指定结点相同的所有结点
测试用例
Input :1 2 3 2 4 5 2
Output:1 3 4 5

struct node *DeleteNode(struct node *L, int e)
{    
    struct node *p=L->next,*q=L;
    if (L==NULL)          
    { 
        printf("链表为空\n");
        return L;
    }
    while(p!=0)
    {
        if(p->data==e)
        {
            q->next=p->next;
            free(p);
            p=q->next;
        }
        else 
        {
            p=p->next;
            q=q->next;
        }

    }
    return L;     
}
发布了46 篇原创文章 · 获赞 19 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/thwwu/article/details/78513284
今日推荐