从表a中删除自第i个元素起共len个元素后,将它们插入到表b中第j个元素之前。
#include <stdio.h>
#include<stdlib.h>
typedef int ElemType;
struct Student
{
ElemType data;
struct Student *next;
} ;
typedef struct Student LIST;
LIST * CreateList()
{
LIST *cur,*prev,*h;
h = NULL;
//char a;
//a = 1;
//手动输入结点个数
int n,i;
printf("输入结点个数:\n");
scanf("%d",&n);
for(i =0; i<n; i++)
{
//申请一块内存
cur =(LIST*) malloc(sizeof(LIST));
/*判断内存分配是否成功*/
// if(!(cur =(LIST*) malloc(sizeof(LIST))))
// {
// printf("内存分配失败");
// return 0;
// }
cur->next = NULL;
//头指针指向头节点
if(h == NULL)
{
h = cur;
}
else
{
prev->next = cur;
}
scanf("%d",&cur->data);
prev = cur;
}
printf("list created successful\n");
return h;
}
void DisplayList(LIST *h)
{
printf("显示函数被执行\n");
LIST *p;
p = h;
// if(p == NULL)
// printf("空链表\n");
while(p != NULL)
{
printf("%d\n",p->data);
p = p->next;
}
printf("显示完毕");
}
LIST* DeleteAndInsertSub(LIST *la, LIST *lb, int i, int j, int len)
//从表a中删除自第i个元素起共len个元素后,将他们插入到表lb中第j个元素之前
{
//if(i<0||j<0||len<10)
// return 0;
LIST *prev, *p,*pi,*previ;
p = la;
//第一步在表a中找到第i个元素
if(i == 1)//如果从第一个节点开始删
{
while(len>0)
{
p = p->next;
len--;
printf("正在执行%d\n",p->data);
}
la = p;
}
else
{
while(i>1)
{
prev = p;
p= p->next;
i--;
}
pi = p;
previ = prev;
//再找到i后面的len个元素
while(len>0)
{
p = p->next;
len--;
}
//删除
previ->next = p;
}
//将la插入到lb的第j个元素之前
//找到a链表的尾结点
LIST *p_last;
p_last = la;
while(p_last->next!=NULL)
{
p_last = p_last->next;
}
//先找到b链表中的第j个元素
if(j == 1)//插在b链表之前
{
p_last->next = lb;//a链表的尾结点指向b链表的首届点
return la;
}
else
{
LIST *pb,*prevb;
pb = lb;
while(j>1)
{
prevb = pb;
pb = pb->next;
j--;
}
//插入
prevb->next = la;
p_last->next = pb;
}
return lb;
}
LIST * DeleteFromBegin(LIST *h, int len)
{
LIST *p;
p = h;
while(len>1)
{
len--;
h = h->next;
}
return h;
}
int main()
{
LIST *la,*lb;
printf("创建链表a\n");
la=CreateList();
DisplayList(la);
printf("创建链表b\n");
lb=CreateList();
DisplayList(lb);
int i,len,j;
printf("删除a链表中的第: 元素起共: 个元素\n");
scanf("%d %d",&i,&len);
printf("插入b表的第: 个元素前\n");
scanf("%d",&j);
lb = DeleteAndInsertSub(la,lb,i,j,len);
// h=DeleteFromBegin(h,len);
DisplayList(lb);
return 0;
}