SWUST OJ(952)

时间:2022-05-22 18:57:05

单链表的插入操作实现

 #include <stdio.h>
#include <stdlib.h> typedef struct LinkList
{
int data;
struct LinkList *next;
}LinkList; void CreateLinkList(LinkList *&L,int n, int *array)
{
L =(LinkList*)malloc(sizeof(LinkList)); //先创建一个带头结点的单链表
L->next = NULL;
LinkList * r = L; //r指针始终指向链表的最后一个节点
for (int i = ; i < n; ++i)
{
LinkList * p =(LinkList*)malloc(sizeof(LinkList));
p->data = *array++;
//将新增的节点用尾插法插入到链表中
p->next = r->next;
r->next = p;
r = p;
} } void InsertLinkList(LinkList *&L, int n, int item, int data)
{
if(item > n || item < )
{
printf("error!");
exit(-);
}
else
{
LinkList *p = L;
for (int i = ; i < item-; ++i)
{
p = p->next;
} LinkList * node =(LinkList*)malloc(sizeof(LinkList));
node->data = data;
node->next = p->next;
p->next = node;
}
} void DisLinkList(LinkList *L)
{
LinkList *p = L->next;
while(p!=NULL)
{
printf("%d ",p->data);
p = p->next;
}
} int main(int argc, char const *argv[])
{
/*int n = 5;
int arry[]={1,2,3,4,5};
int item = 3;
int data = 6;*/ int n,item,data;
int *arry; scanf("%d",&n);
arry = (int*)malloc(n*sizeof(int));
for (int i = ; i < n; ++i)
{
scanf("%d",&arry[i]);
}
scanf("%d",&item);
scanf("%d",&data); LinkList * L;
CreateLinkList(L,n,arry);
InsertLinkList(L,n,item,data);
DisLinkList(L);
return ;
}