#include <stdio.h>
#include <stdlib.h>
typedef struct Node
{
int data;
struct Node *next;
} node;
node *in(node *p,int x)//插入節點
{
node *q;
q=(node *)malloc(sizeof(node));
q->data=x;
q->next=NULL;
q->next=p->next;
p->next=q;
}
node *search(node *head,int m)//尋找插入點
{
node *p;
p=head;//如果p=head—>next; 會出錯,因爲沒插入節點的鏈表的head的next爲空
while(m--&&p->next!=NULL)
{
p=p->next;
}
return p;
}
void output(node *head)//輸出鏈表
{
node *p;
p=head->next;
while (p!=NULL)
{
if (p->next==NULL)
printf("%d\n",p->data);
else
printf("%d ",p->data);
p=p->next;
}
}
int main()
{
node *head;
int i,n,m,x;
node *l;
while(~scanf("%d",&n))
{
head=(node *)malloc(sizeof(node));
head->next=NULL;
for (i=0; i<n; i++)
{
scanf("%d %d",&m,&x);
l=search(head,m);
in(l,x);
}
output(head);
}
return 0;
}
ps:第一次獨立完成鏈表的題,雖然只是最簡單的插入,但還是有點激動,留念!