#include <iostream>
using namespace std;
typedef struct Node
{
int val;
Node *next;
}node;
node* mycreat()
{
node *head=NULL,*p=NULL,*ne=NULL;
head=(node*)malloc(sizeof(node));
p=head;
int v;
while(scanf("%d",&v))
{
if(v==0) break;
ne=(node*)malloc(sizeof(node));
ne->val=v;
p->next=ne;
p=ne;
}
p->next=NULL;
return head;
}
void myinsert(int n,int in,node *head)
{
node *p=NULL;
p=head->next;//从头指针开始
int c=0;//计数器
while(p!=NULL)//只要接下来的指针不为空
{
c++;
if(c==n)//找到插入点
{
node *q=NULL;//额外设立一个节点
q=(node*)malloc(sizeof(node));
q->val=in;//节点的值存为插入值
q->next=p->next;//插入节点接上下一节点
p->next=q;//上一节点接上插入节点
break;
}
p=p->next;//一个个节点遍历下去
}
return;
}
void myprint(node *head)
{
int f=0;
node *p=NULL;
p=head->next;
while(p!=NULL)
{
if(f==0)
printf("%d",p->val);
else
printf(" %d",p->val);
p=p->next;
f++;
}
printf("\n");
return;
}
int main()
{
int n,in;
node *head=NULL;
while(~scanf("%d%d",&n,&in))
{
if(n==0&&in==0) break;
head=mycreat();
myinsert(n,in,head);//插入
myprint(head);
}
return 0;
}
单链表的插入
最新推荐文章于 2021-05-29 17:03:45 发布