创建(尾插法)带头结点的链表,并在指定位置插入一个数据,如果成功,则输出插入后链表中的所有数据,如果插入失败,则输出“INSERT ERROR”
输入
输出第一行输入一组整数,以-1作为结束标志
第二行输入两个整数x和pos
样例输入插入成功,输出整个链表数据,如果失败则显示“INSERT ERROR”
样例输出1 2 3 4 5 -1 111 3
带填充标签的C/C++原程序1 2 111 3 4 5
#include"stdio.h"
#include"stdlib.h"
struct node {
int data;
struct node *next;
};
typedef struct node linknode;
linknode * createfromtail();
void printlink(linknode *h);
void destroylink(linknode *h);
int insert( linknode *h,int x ,int pos);
int main()
{
linknode *head=NULL;
int x;
int pos,r;
head=createfromtail();
scanf("%d%d",&x,&pos);
r=insert(head,x,pos);
if (r<1) //插入失败
printf("INSERT ERRORn");
else //插入成功,输出链表
printlink(head);
destroylink(head);
return 0;
}
linknode * createfromtail()
{
linknode *head,*tail,*p;
int s;
head=(linknode *)malloc(sizeof(linknode ));
head->next=NULL;
@@1
@@1
return head;
}
void destroylink(linknode *h)
{
linknode *q;
while(h!=NULL)
{
q=h;
h=h->next;
free(q);
}
}
void printlink(linknode *h)
{
linknode *p=h->next;
while(p)
{
printf("%d ",p->data);
p=p->next;
}
}
@@2
@@2
代码答案
注意第一个和最后一个的位置讨论,且本题是带头结点的链表
#include"stdio.h"
#include"stdlib.h"
struct node {
int data;
struct node *next;
};
typedef struct node linknode;
linknode * createfromtail();
void printlink(linknode *h);
void destroylink(linknode *h);
int insert( linknode *h,int x ,int pos);
int main()
{
linknode *head=NULL;
int x;
int pos,r;
head=createfromtail();
scanf("%d%d",&x,&pos);
r=insert(head,x,pos);
if (r<1) //插入失败
printf("INSERT ERRORn");
else //插入成功,输出链表
printlink(head);
destroylink(head);
return 0;
}
linknode * createfromtail()
{
linknode *head,*tail,*p;
int s;
head=(linknode *)malloc(sizeof(linknode ));
head->next=NULL;
tail=head;
while(scanf("%d",&s),s!=-1)
{
p=(linknode *)malloc(sizeof(linknode));
p->data=s;
p->next=NULL;
tail=tail->next=p;
}
return head;
}
void destroylink(linknode *h)
{
linknode *q;
while(h!=NULL)
{
q=h;
h=h->next;
free(q);
}
}
void printlink(linknode *h)
{
linknode *p=h->next;
while(p)
{
printf("%d ",p->data);
p=p->next;
}
}
int insert( linknode *h,int x ,int pos)
{
linknode *p=h->next,*q=NULL;
if(pos>0)
{
linknode *s=(linknode *)malloc(sizeof(linknode ));
s->data=x;
int n=0;
while(p->next&&++nnext;
}
if(n==pos||n+1==pos)
{
if(q==NULL) { s->next=p;h->next=s; }
else if(p->next==NULL) { s->next=NULL;p->next=s; }
else { s->next=p;q->next=s; }
return 1;
}
}
return 0;
}



