如何删除此代码中的重复代码?

我是一名新的C99程序员,需要社区的帮助。

我编写了以下函数,该函数接收一个节点(或简称为Node)的两个指针和一个指向该节点(或* Node)的指针的指针,然后将它们合并为一个排序的节点。

已给出

typedef struct node_t {
    int x;
    struct node_t *next;
} *Node;

typedef enum {
    SUCCESS = 0,MEMORY_ERROR,EMPTY_LIST,UNSORTED_LIST,NULL_ARGUMENT,} ErrorCode;

int getListLength(Node list);

bool isListsorted(Node list);

这是我编写的代码:

ErrorCode mergeSortedLists(Node list1,Node list2,Node *merged_out)
{
    if (merged_out==NULL)
        return NULL_ARGUMENT;
    if (list1==NULL || list2==NULL)
        return EMPTY_LIST;
    if (!isListsorted(list1) || !isListsorted(list2))
        return UNSORTED_LIST;
    Node ptr=*merged_out;
    int list1_len=getListLength(list1),list2_len=getListLength(list2);
    for (int i=0;i<list1_len+list2_len;i++)
    {
        int min=0;
        if (list1!=NULL && (list2==NULL || (list2!=NULL && list1->x<=list2->x))){
            min = list1->x;
            list1=list1->next;
        }
        else{
            min=list2->x;
            list2=list2->next;
        }
        ptr->x=min;
        if (i==list1_len+list2_len-1){
            ptr->next=NULL;//The next for the last Node should be Null
            continue;
        }
        ptr->next=malloc(sizeof(*ptr));
        if (ptr->next==NULL){
            //We should Free all previosly allocated memory
            //except for the first node since it was not allocated via malloc
            return MEMORY_ERROR;
        }
        ptr=ptr->next;
    }
    ptr=NULL;
    return SUCCESS;
}

但是在检查了我的代码后,我被告知它有很多代码重复(更确切地说,在他的for循环内),应该使用外部函数进行纠正,您是否注意到任何代码重复?以及如何解决这个问题,有什么想法?

hjh198966 回答:如何删除此代码中的重复代码?

暂时没有好的解决方案,如果你有好的解决方案,请发邮件至:iooj@foxmail.com
本文链接:https://www.f2er.com/2458576.html

大家都在问