单链表如何不遍历删除一个元素?

问题描述 投票:0回答:0

这是确切的问题: 编写下面 delete_min_max 例程的实现,从“head”开始的链表中删除最大和最小元素,并返回新的头(如果适用)以及与最小值和最大值相对应的已删除节点。您可以假设所有链表元素都具有不同的值。如果链表只包含一个元素,则同一元素被认为是最小值和最大值。您不得在您的实现中调用任何函数。您可以在您的实现中对链表中的所有元素进行一次迭代。确保您的实施中没有语法错误。

这是我到目前为止写的代码

struct node{
    int val;
    struct node* next;
};

struct delete_info {
    struct node *head; // head of the new linked list
    struct node *min; // the deleted node that contains minimum value
    struct node *max; // the deleted node that contains maximum value
};

struct delete_info delete_min_max(struct node *head){
    struct delete_info delete;
    struct node* max=head;
    struct node* min=head;
    struct node* tmp=head;
    while (tmp!=NULL){
        if ((tmp->val)>(max->val)){
            max=tmp;
        }
        if ((tmp->val)<(min->val)){
            min=tmp;
        }
        tmp=tmp->next;
    }

    if (max->val==head->val || min->val==head->val){
        delete.head=head->next;
        head=head->next;
        if (head!=NULL){
            if (max->val==head->val){
            delete.head=head->next;
            head=head->next;
            }
        }
        if (head!=NULL){
            if (min->val==head->val){
                delete.head=head->next;
                head=head->next;
            }
        }
    }else{
        delete.head=head;
    }
    delete.max=max;
    delete.min=min;
    return delete;
}

我已经遍历了一次元素,找出最大值和最小值。现在我需要在同一个函数中删除这些值,但由于问题中给出的限制,我不能再遍历列表一次。另外,根据问题中提供的骨架代码,我不能使用双向链表。如何修改我的函数以包括在单个循环中删除和搜索最大值和最小值。

c linked-list singly-linked-list doubly-linked-list dsa
© www.soinside.com 2019 - 2024. All rights reserved.