注册 登录
编程论坛 C语言论坛

两链表合并出错,麻烦各位指出问题

wxdbymyself 发布于 2021-09-19 14:21, 1518 次点击
我想写一个将两个升序链表合并(去重复值)的函数,但是写完了之后输出时只有表头和表尾会输出,求解为啥,这是我的函数
ElemSH* SlectSheng(ElemSH* h1,ElemSH* h2){
    ElemSH *hn,*t,*ins;
    hn=NULL;
    while(h1&&h2){
        if(h1->date<h2->date){
            ins=h1;
            h1=h1->next;
        }
        else{
            ins=h2;
            h2=h2->next;
        }
        if(!hn){
            hn=t=ins;
        }
        else{
            if(t->date==ins->date){
                t->next=ins->next;
                free(ins);
            }
            else{
                t->next=ins;
            }
        }
    }
    return hn;
}
2 回复
#2
自由而无用2021-09-19 15:08
https://blog.
#3
沈和2021-09-19 17:52
回复 楼主 wxdbymyself
程序代码:



        else{
            if(t->date==ins->date){
                t->next=ins->next;
                free(ins);
            }
            else{
                t->next=ins; // 赋值后,t需要指向下一个元素。如果没有指向下一个元素,中间的元素会被覆盖,从而只剩下头和尾。
            }
        }
    }
    return hn;
}

#4
沈和2021-09-19 18:00
回复 3楼 沈和
引用的那块代码,if那一块可能也有问题。调试看看应该不难发现
#5
自由而无用2021-09-19 21:10
//online parser: https://www.bccn.net/run/
程序代码:
#include <stdio.h>
#include <stdlib.h>

#pragma GCC diagnostic ignored "-Wpointer-to-int-cast"

typedef struct _ElemSH
{
    int data;
    struct _ElemSH *next;
}ElemSH, *PSH;

int main(int argc, char *argv[]);

void* init_ElemSH(void *h, void *m)
{
    int i;
   
    //BUG_ON(!h);
#define CAST2ELEM(v, idx) ((PSH)(v))[idx]
    for(i = 0; i < 10; i++) {
typedef unsigned char uint8_t;
        CAST2ELEM(h, i).data = ((uint8_t *)m)[i] % 10;
        CAST2ELEM(h, i).next = (PSH)(&CAST2ELEM(h, i + 1));
    }
   
    return h;
}

void print_ElemSH(void *h)
{
    int i;
   
    //BUG_ON(!h);
    for(i = 0; i < 20; i++) {
        printf("h[%02d]->data = %d\t", i, (&CAST2ELEM(h, i))->data);
#define MASK_A(_a) _a & 0xfff
        printf("h[%02d]->next = 0x%x\n", i, MASK_A((int)(&CAST2ELEM(h, i))->next));
    }
}

void* merge_ElemSH(void *va, void *vb)
{
    int i;

    //BUG_ON(!h);
    for(i = 0; i < 10; i++) {
        if(CAST2ELEM(va, i).data <= CAST2ELEM(vb, i).data) {
            CAST2ELEM(va, i).next = &CAST2ELEM(vb, i);
            CAST2ELEM(vb, i).next = &CAST2ELEM(va, i + 1);
        } else {
            //do sth...
        }
    }
   
    return va;
}

int main(int argc, char *argv[])
{
    struct _ElemSH ha[10];
    struct _ElemSH hb[10];
   
    init_ElemSH(ha, main);
#define safe_region +0x100
    init_ElemSH(hb, main + safe_region);
//#define PRINT_ON
#ifdef PRINT_ON
    puts("----------ha & hb list--------");
    print_ElemSH(ha);
    puts("----------merge list--------");
    print_ElemSH(merge_ElemSH(ha, hb));
#endif

    return 0;
}

index & pointer just 4 fun
1