6-3 Combination of two ordered linked list sequences

6-3 Combination of two ordered linked list sequences (15 points)

This question requires the realization of a function to merge the sequence of increasing integers represented by two linked lists into a sequence of non-decreasing integers.

Function interface definition:

List Merge( List L1, List L2 );

The List structure is defined as follows:

typedef struct Node *PtrToNode;
struct Node {
    
    
    ElementType Data; /* 存储结点数据 */
    PtrToNode   Next; /* 指向下一个结点的指针 */
};
typedef PtrToNode List; /* 定义单链表类型 */

L1 and L2 are a given singly-linked list with a leading node, and the data stored at the node is in increasing order; the function Merge will merge L1 and L2 into a non-decreasing integer sequence. The node in the original sequence should be used directly, and the linked list head pointer of the leading node after the merge should be returned.

Sample referee test procedure:

#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 ); /* 细节在此不表;空链表将输出NULL */

List Merge( List L1, List L2 );

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

/* Your code will be embedded here */

Input sample:

3

1 3 5

5

2 4 6 8 10

Sample output:

1 2 3 4 5 6 8 10

NULL

NULL

List Merge( List L1, List L2 ){
    
    
    List head = (List)malloc(sizeof(List));
    List p = head;
    List a = L1->Next;
    List b = L2->Next;
    while(a && b){
    
    
        if(a->Data > b->Data){
    
    
            p->Next = b;
            b = b->Next;
        }else{
    
    
            p->Next = a;
            a = a->Next;
        }
        p = p->Next;
    }
    p->Next = a ? a : b;
    L1->Next = NULL;
    L2->Next = NULL;
    return head;
}

Guess you like

Origin blog.csdn.net/weixin_51198300/article/details/114887710