题目描述:
LeetCode(203)
通过的代码

struct ListNode* removeElements(struct ListNode* head, int val)
{
    struct ListNode *p,*p_prior;
    struct ListNode *head_temp=(struct ListNode *)malloc(sizeof(ListNode));
    /*新开一个结点啊。作为链表的新头结点。不新开头结点的话,挺麻烦的。
    如果只是
    p_prior=head;
    p=head;
    这样也能通过一半的用例,但是如果val为1吧,【1,1】的时候就会出错,输出是【1】,其实应该是【】才对。还有【1】的输出也为【1】。
    */
    head_temp->next=head;
    p_prior=head_temp;
    p=head;
    while(p!=NULL)
    {
        if(p->val==val)
        {
           p_prior->next=p->next;
           p=p_prior->next;
        }
        else
        {
           p_prior=p;
           p=p->next;
        }
    }
    return head_temp->next;
}

提交结果
LeetCode(203)

完整代码:

#include <stdio.h>
#include <algorithm>
struct ListNode
{
    int val;
    struct ListNode *next;
};

typedef struct ListNode LNode;
typedef struct ListNode *LNode_Pointer;
struct ListNode* removeElements(struct ListNode* head, int val)
{
    struct ListNode *p,*p_prior;
    struct ListNode *head_temp=(struct ListNode *)malloc(sizeof(ListNode));
    //新开一个结点啊。作为链表的新头结点
    head_temp->next=head;
    p_prior=head_temp;
    p=head;
    while(p!=NULL)
    {
        if(p->val==val)
        {
           p_prior->next=p->next;
           p=p_prior->next;
        }
        else
        {
           p_prior=p;
           p=p->next;
        }
    }


    return head_temp->next;
}



void Tail_Insert_List(LNode_Pointer &head,LNode_Pointer &tail,int val)//&tail。不加&的话每次的tail的值还是head的值
{
    LNode_Pointer q=(LNode_Pointer)malloc(sizeof(LNode));
    if(tail!=NULL)
    {
        q->val=val;
        tail->next=q;
        tail=tail->next;
        tail->next=NULL;
    }
    else
    {
        q->val=val;
        tail=q;
        tail->next=NULL;
        head=tail;//注意这里。不这样的话主函数的head仍然是0。
    }


}
void printf_List(LNode_Pointer p)
{
    while(p!=NULL)
    {
        if(p->next!=NULL)
        {
           printf("%d(地址=%p)->",p->val,p);
           //printf("%d->",p->val,p);
           p=p->next;
        }
        else
        {
           printf("%d(地址=%p)",p->val,p);
           //printf("%d",p->val,p);
           p=p->next;
        }
    }
}



int main()
{
    int val;
    LNode_Pointer head=(LNode_Pointer)malloc(sizeof(LNode));
    head=NULL;
    LNode_Pointer tail=(LNode_Pointer)malloc(sizeof(LNode));
    tail=head;
    while(scanf("%d",&val)!=EOF)
    {
        Tail_Insert_List(head,tail,val);
    }

    printf_List(head);

    printf("\n");

    LNode_Pointer head_return=removeElements(head,6);
    printf_List(head_return);

    return 0;
}

本地运行结果:
LeetCode(203)

相关文章: