zoukankan      html  css  js  c++  java
  • 两个有序链表序列的合并

    本题要求实现一个函数,将两个链表表示的递增整数序列合并为一个非递减的整数序列。

    函数接口定义:

    List Merge( List L1, List L2 );
    

    L1和L2是给定的带头结点的单链表,其结点存储的数据是递增有序的;函数Merge要将L1和L2合并为一个非递减的整数序列。应直接使用原序列中的结点,返回归并后的带头结点的链表头指针。

    裁判测试程序样例:

    #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;
    }
    /* 你的代码将被嵌在这里 */
    

    输入样例:

    3
    1 3 5
    5
    2 4 6 8 10

    输出样例:

    1 2 3 4 5 6 8 10
    NULL
    NULL

    我的代码C(gcc 6.5.0)

    List Merge(List L1, List L2) {
    	List L, temp, l1, l2;
    	L = (List)malloc(sizeof(struct Node));
    	L->Next = NULL;
    	if (L1->Next == NULL && L2->Next == NULL) { //两个空链表的判断
    		return L;
    	}
    	temp = L;
    	l1 = L1->Next;
    	l2 = L2->Next;
    	while (l1 != NULL && l2 != NULL) {
    		if (l1->Data > l2->Data) {
    			temp->Next = l2;
    			l2 = l2->Next;
    		}
    		else {
    			temp->Next = l1;
    			l1 = l1->Next;
    		}
    		temp = temp->Next;
    	}
    	while (l1) {
    		temp->Next = l1;
    		temp = temp->Next;
    		l1 = l1->Next;
    	}
    	while (l2) {
    		temp->Next = l2;
    		temp = temp->Next;
    		l2 = l2->Next;
    	}
    	L1->Next = NULL;
    	L2->Next = NULL;
    	return L;
    }
    
  • 相关阅读:
    51Nod1136--欧拉函数
    ubuntu裸机镜像问题
    汉诺塔问题
    lwm2m协议
    WPF自定义控件与样式(4)-CheckBox/RadioButton自定义样式
    图解大顶堆的构建、排序过程
    WindowsService开发简单入门
    数据结构和算法参考网址
    c#创建windows服务入门教程实例
    C#比较两个对象是否为同一个对象。 Visual Studio调试器指南---多线程应用程序调试(一)
  • 原文地址:https://www.cnblogs.com/TangYJHappen/p/13624209.html
Copyright © 2011-2022 走看看