站点图标 陌路寒暄

两个链表之间问题(线性表)

两个链表之间问题(线性表)

时间: 1ms        内存:128M

描述:

已知两个单链表A和B,其头指针分别为heada和headb,编写一个过程从单链表A中删除自第i个元素起的共len个元素,然后将单链表A插入到单链表B的第j个元素之前。

输入:

前三个数分别表示i,len,j

一个整数m,表示A链表的长度m。

m个数表示A链表中的m个数据元素。

一个整数n,表示B链表的长度n。

n个数表示B链表中的n个数据元素。

输出:

操作后的结果。

示例输入:

 1 3 5

11

13 5 14 62 3 43 71 5 72 34 5

15

5 20 3 53 7 81 5 42 6 8 4 6 9 10 23

示例输出:

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


提示:

参考答案(内存最优[752]):

#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)!=EOF)){                 
        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%d%d;",&i,&len,&j);
	scanf("%d",&m);
    heada = creat(m);
        scanf("%d",&n);
	headb = creat(n);
	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;
}

参考答案(时间最优[0]):

#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)!=EOF)){                 
        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%d%d;",&i,&len,&j);
	scanf("%d",&m);
    heada = creat(m);
        scanf("%d",&n);
	headb = creat(n);
	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;
}

题目和答案均来自于互联网,仅供参考,如有问题请联系管理员修改或删除。

退出移动版