线性表(本例是单向链表)的合并

该博客记录了使用C语言实现线性表合并的代码。定义了双向链表节点结构体,实现了创建链表、计算链表长度、查找元素位置、追加元素等功能,最后在主函数中完成两个线性表的合并,并输出合并后链表的长度和元素。

仅供个人学习记录使用,欢迎指正!!!!!!!

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

typedef struct Dounode {         //线性表的合并
    int data;
    struct Dounode* prior;
    struct Dounode* next;
}*dnhead1  ;
struct Dounode* dcreate(int len) {
    struct Dounode* head = (struct Dounode*)malloc(sizeof(struct Dounode));//头节点非首元结点
    struct Dounode* p1 = NULL,*p2 = head;
    for (int i = 0; i < len; i++) {
        p1 = (struct Dounode*)malloc(sizeof(struct Dounode));
        scanf("%d",&p1->data);
        p2->next = p1;
        p2 = p1;
    }
    p2->next = NULL;
    return head;
}
int listlenth(struct Dounode* head) {
    int count = 0;
    struct Dounode* p0 = head;
    while (p0->next) {
        count++;
        p0 = p0->next;
    }
    return count;
}
int getelem(struct Dounode* head, int elem) {
    int outcome = 0;
    struct Dounode* h=head;
    for (int i = 0; i < listlenth(head); i++) {
        if (h->next->data == elem) {
            outcome = i + 1;
            break;
        }
        h = h->next;
    }
    return outcome;
}
void listappend(struct Dounode* head,int elem) {
    struct Dounode* tail=head;
    while (tail->next) {
        tail = tail->next;
    }
    struct Dounode* newp= (struct Dounode*)malloc(sizeof(struct Dounode));
    newp->data = elem;
    tail->next = newp;
    newp->next = NULL;
}
int main() {
    struct Dounode* dcreate(int len);
    int listlenth(struct Dounode* head);
    int getelem(struct Dounode* head, int elem);
    void listappend(struct Dounode* head, int elem);
    int len1 ,len2;
    scanf("%d %d", &len1, &len2);
    struct Dounode* list1 = dcreate(len1);
    struct Dounode* list2 = dcreate(len2);
    struct Dounode* tempp1=list1->next,*tempp2=list2->next;
    for (int i = 0; i < len1; i++) {
        if (!getelem(list2,tempp1->data)) {
            listappend(list2, tempp1->data);
        }
        tempp1 = tempp1->next;
    }
    printf("%d\n", listlenth(list2));
    for (int i = 0; i < listlenth(list2); i++) {
        printf("%d ", tempp2->data);
        tempp2 = tempp2->next;
    }
    return 0;
}
test:4 3
7 5 3 11
2 6 3

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值