标题:数据结构:单链表中在P结点前插入S结点
在数据结构的习题中偶然看到了一个题目
已知在单链表中P不是首元结点也不是尾元结点,在P结点前插入S结点
#include<stdio.h>
#include<malloc.h>
typedef struct node
{
int date;
struct node * next;
}Node,*LinkList;
LinkList CreatList(LinkList L)
{
int i;
LinkList node,end;
L=(LinkList)malloc(sizeof(Node));
end=L;
for(i=0;i<5;i++)
{
node=(LinkList)malloc(sizeof(Node));
node->date=i;/*为了表示方便,这里采用常用的方法:将i的值当作结点中存放的信息*/
end->next=node;
end=node;
}
end->next=NULL;
return L;
}
void Show(LinkList L)
{
L=L->next;
while(L!=NULL)
{
printf("%d ",L->date);
L=L->next;
}
printf("\n");
}
int main()
{
LinkList L=CreatList(L);
Show(L);/*创建好的链表输出应为:0 1 2 3 4*/
LinkList t=L;
LinkList P,S;
int i;
S=(LinkList)malloc(sizeof(Node));/*给S分配空间*/
S->date=10;/*这里将10作为S结点中存放的信息*/
for(i=0;i<2;i++)t=t->next;
P=t;/*在这里以P为第二个结点为例*/
/*上述都是为将S插在P前面所做的准备,下面开始进行插入*/
LinkList Q;
Q=P;
P=L;
while(P->next!=Q)P=P->next;
P->next=S;
S->next=Q;
Show(L);/*插入后的链表输出应为:0 10 1 2 3 4*/
}
运行结果如下:
0 1 2 3 4
0 10 1 2 3 4