《C语言及程序设计》实践参考——链表的合并

来源:互联网 发布:谁的java视频教程好 编辑:程序博客网 时间:2024/06/18 15:42

返回:贺老师课程教学链接

【项目1-链表的合并】
输入一个整数m,表示A链表的长度,再输入m个数作为A链表中的m个数据元素,建立链表A,其头指针为heada。输入一个整数n,表示B链表的长度,再输入n个数表示B链表中的n个数据元素,建立链表B,其头指针为headb。输入i、len、j,将要从单链表A中删除自第i个元素起的共len个元素,然后将单链表A插入到单链表B的第j个元素之前。最后输出操作后的链表B。
例如,输入:

11
13 5 14 62 3 43 71 5 72 34 5 (11个数构成链表A)
15
5 20 3 53 7 81 5 42 6 8 4 6 9 10 23(15个数构成链表B )
1 3 5(从单链表A中删除自第1个元素起的共3个元素,然后将单链表A插入到单链表B的第5个元素之前)

输出:

5 20 3 53 62 3 43 71 5 72 34 5 7 81 5 42 6 8 4 6 9 10 23

[参考解答]

#include<stdio.h>#include<malloc.h>struct node{    int data;    struct node *next;};struct node *creat(int m){    struct node *head,*p,*q;    head=(struct node *)malloc(sizeof(struct node));    q = head;    while(m--)    {        p=(struct node *)malloc(sizeof(struct node));         scanf("%d",&p->data);         q->next = p;         q = p;    }    q->next = NULL;    return head;}int main(){    int i,len,j;    int m,n;    struct node *heada,*headb,*p,*q;    scanf("%d",&m);    heada = creat(m);    scanf("%d",&n);    headb = creat(n);    scanf("%d%d%d;",&i,&len,&j);    p = q = heada;    while(--i)    {        p = p->next;        q = q->next;    }    while(len--)    {        q = q->next;    }    p->next = q->next;    while(q->next != NULL)        q = q->next;    p=headb;    while(--j)        p = p->next;    q->next = p->next;    p->next = heada->next;    p = headb->next;    while(p != NULL)    {        printf("%d ",p->data);        p = p->next;    }    return 0;}
1 0
原创粉丝点击