设有链表A和B,编写算法将链表B插入到A的元素X后。
(即A:a1,a2,x,ay,an;B:b1,b2,bn;结果是a1,a2,x,bi,b2,bn,ay,an)
思路:首先定义出链点和链表;然后用循环找到x的位置,让其next域为B表表头h2。再用循环将指针指向B表表尾,使其next域为A表中x下一个元素地址。
实现:
typedef struct node_type
{
int data;
struct node_type * next;
}node_type ;
typedef struct list_type{
node_type *head;
int length;
}list_type;
int insert1(node *h1, node *h2, int x)
{
node *p, *q, *temp;
p=h1;
q=h2;
while(p!=NULL&&p->data!=x)
{
p=p->next;
}
if(p->data!=x)
{
printf("x is invalid");
return;
}
temp=p;
p->next=q;
while(q!=NULL)
{
q=q->next;
}
q->next=temp;
}
{
int data;
struct node_type * next;
}node_type ;
typedef struct list_type{
node_type *head;
int length;
}list_type;
int insert1(node *h1, node *h2, int x)
{
node *p, *q, *temp;
p=h1;
q=h2;
while(p!=NULL&&p->data!=x)
{
p=p->next;
}
if(p->data!=x)
{
printf("x is invalid");
return;
}
temp=p;
p->next=q;
while(q!=NULL)
{
q=q->next;
}
q->next=temp;
}
本文介绍了一种链表插入算法,该算法将链表B插入到链表A的指定元素X之后,通过查找X的位置并调整指针来实现。具体步骤包括定位X节点,将B表头连接至X节点后,并确保B表尾正确指向A表中X后的元素。
867

被折叠的 条评论
为什么被折叠?



