zoukankan      html  css  js  c++  java
  • 合并两个单链表

      (2018-02-14 代码更新)

      marge.h:

    #ifndef __MARGELINKLIST_H_
    #define __MARGELINKLIST_H_
    
    typedef int Type;
    
    typedef struct Node
    {
        struct Node*next;
        Type data;
    }Node;
    
    /* 定义函数 */
    Node*CreateLinkList_A();
    Node*CreateLinkList_B();
    Node*Marge();
    
    #endif

      marge.c:

    #include <stdio.h>
    #include <stdlib.h>
    #include "marge.h"
    
    Node*CreateLinkList_A(int length)
    {
        Node * A, * t, * s;
        
        A = (Node*)malloc(sizeof(Node));
        t = A;
        for(int i = 0; i < length; i++)
        {
            s = (Node*)malloc(sizeof(Node));
            s->data = i + 1;
            t->next = s;
            t = s;
        }
        t->next = A->next;
        
        return t;  /* 返回尾结点 */
    }
    
    Node*CreateLinkList_B(int length)
    {
        Node * B, * r, * c;
        
        B = (Node*)malloc(sizeof(Node));
        r = B;
        for(int i = 0; i < length; i++)
        {
            c = (Node*)malloc(sizeof(Node));
            c -> data = 2 * i + 1;
            r -> next = c;
            r = c;
        }
        r -> next = B;/* 注:因为释放时释放的是该链表的头结点,所以尾结点指向头结点(头结点没有数据),如果指向头的后一个,则会缺少第一个数 */
        
        return r;   /* 返回尾结点 */
    }
    
    Node*Marge(Node*a, Node*b)
    {
        Node*p;
        
        p = a->next;
        a->next = b->next->next;
        free(b->next);
        b->next = p;
        
        return p;   /* 返回连接好的新链表的头结点 */
    }

      main.c:

    #include <stdio.h>
    #include <stdlib.h>
    #include "marge.h"
    
    int main()
    {
        Node*p;
        
        p = Marge(CreateLinkList_A(5), CreateLinkList_B(6));
        while(p)
        {
            printf("%d ", p->data);
            p = p->next;
        }
        
        return 0;
    }
    

      

  • 相关阅读:
    python写入csv文件中文乱码解决方案
    高质量代码有三要素:可读性、可维护性、可变更性
    CFile
    BMP格式图像的显示
    SAP BW 学习笔记(一)
    SAP BW 学习笔记(五)
    SAP BW 学习笔记(二)
    SAP BW 学习笔记(三)
    SAP BW 学习笔记(四)
    CRM 5.0 Marketing – BW integrated topics summary
  • 原文地址:https://www.cnblogs.com/darkchii/p/7347084.html
Copyright © 2011-2022 走看看