首页 > 解决方案 > 如何更改输入链表而不返回

问题描述

Q:合并两个链表,返回合并后的List和两个空链表。

输入:

3
1 3 5
5
2 4 6 8 10

期望的输出:

1 2 3 4 5 6 8 10 
NULL
NULL

但我得到了:

1 2 3 4 5 6 8 10 
1 3 5
2 4 6 8 10

我的代码:

#include <stdio.h>

#include <stdio.h>
#include <stdlib.h>

typedef int ElementType;
typedef struct Node *PtrToNode;
struct Node {
    ElementType Data;
    PtrToNode   Next;
};
typedef PtrToNode List;

List Read();
void Print( List L );

List Merge( List L1, List L2 );
void C(List L);

int main()
{
    List L1, L2, L;
    L1 = Read();
    L2 = Read();
    L = Merge(L1, L2);
    Print(L);
    C(L1);
    Print(L1);
    Print(L2);
    
    return 0;
}


void C(List L){
    L = L->Next;
}

List Merge( List L1, List L2 ){
    List prehead = (List)malloc(sizeof(struct Node));
    List t = prehead;
    while(L1&&L2){
        if(L1->Data < L2->Data){
            List node = (List)malloc(sizeof(struct Node));
            node->Data = L1->Data;
            t->Next = node;
            t = t->Next;
            L1 = L1->Next;
        }
        else{
            List node = (List)malloc(sizeof(struct Node));
            node->Data = L2->Data;
            t->Next = node;
            t = t->Next;
            L2 = L2->Next;
        }
    }
    while(L1){
        List node = (List)malloc(sizeof(struct Node));
        node->Data = L1->Data;
        t->Next = node;
        t = t->Next;
        L1 = L1->Next;
    }
    while(L2){
        List node = (List)malloc(sizeof(struct Node));
        node->Data = L2->Data;
        t->Next = node;
        t = t->Next;
        L2 = L2->Next;
    }
    t->Next = NULL;
    return prehead->Next;
}

List Read(){
    int n;
    scanf("%d",&n);
    List prehead = (List)malloc(sizeof(struct Node));
    List L = prehead;
    if(n==0) return NULL;
    for(int i=0; i<n; i++)
    {
        List node = (List)malloc(sizeof(struct Node));
        scanf("%d",&node->Data);
        L->Next = node;
        L = L->Next;
       
    }
    List node = prehead;
    List head = prehead->Next;
    free(node);
    L->Next = NULL;
    return head;
}

void Print(List L){
    if(!L) printf("NULL");
    List p = L;
    int flag = 0;
    while(p){
        if(!flag)
            flag = 1;
        else
            printf(" ");
        printf("%d",p->Data);
        p = p->Next;
    }
    printf("\n");
}

一切运作良好。但总的来说,它并没有改变任何东西。

标签: clinked-list

解决方案


推荐阅读