本题要求实现带头结点的单链表插入操作,插入成功返回1,否则返回0。
函数接口定义:
int insert_link ( LinkList L,int i,ElemType e);
L是单链表的头指针,i为插入位置,e是插入的数据元素,插入成功返回1,否则返回0。
裁判测试程序样例:
#include <stdio.h>
#include <stdlib.h>
typedef int ElemType;
typedef struct LNode
{
ElemType data;
struct LNode *next;
}LNode,*LinkList;
LinkList Create();/* 细节在此不表 */
void print( LinkList L);
int insert_link ( LinkList L,int i,ElemType e);
int main()
{
int position,insert_data;int flag;
LinkList L = Create();
scanf("%d",&position);
scanf("%d",&insert_data);
flag=insert_link(L,position,insert_data);
if(flag)
{
print(L);
}
else
{
printf("Wrong Position for Insertion");
}
return 0;
}
void print(LinkList L)
{
LinkList p;
p=L->next;
while (p)
{
printf("%d ", p->data);
p =p->next;
}
}
/* 请在这里填写答案 */
输入格式:
输入数据为三行,第一行是若干正整数,最后以-1表示结尾(-1不算在序列内,不要处理)。所有数据之间用空格分隔。 第二行数据是插入位置,第三行数据是被插入元素值。
输入样例:
1 2 3 4 5 6 -1
2
100
输出样例:
1 100 2 3 4 5 6
代码:(直接可以运行)
#include <stdio.h>
#include <stdlib.h>
typedef int ElemType;
typedef struct LNode
{
ElemType data;
struct LNode *next;
}LNode,*LinkList;
LinkList Create();/* 细节在此不表 */
void print( LinkList L);
int insert_link ( LinkList L,int i,ElemType e);
int main()
{
int position,insert_data;int flag;
LinkList L = Create();
scanf("%d",&position);
scanf("%d",&insert_data);
flag=insert_link(L,position,insert_data);
if(flag)
{
print(L);
}
else
{
printf("Wrong Position for Insertion");
}
return 0;
}
void print(LinkList L)
{
LinkList p;
p=L->next;
while (p)
{
printf("%d ", p->data);
p =p->next;
}
}
/* 请在这里填写答案 */
LinkList Create()
{
LinkList L, p, s;
int e;
L = (LinkList)malloc(sizeof(LNode));
L->next = NULL;
p = L;
scanf("%d", &e);
while (e != -1)
{
s = (LinkList)malloc(sizeof(LNode));
s->data = e;
p->next=s;
p = s;
scanf("%d", &e);
}
p->next = NULL;
return L;
}
int insert_link ( LinkList L,int i,ElemType e)
{
if(i<=0) return 0;//插入位置不在范围内,错误
int cnt = 1;//下标从1开始
//因为需要在指定位置插入元素,因此需要用两个指针
LinkList p = L;
LinkList pre = p;
if(!L) return 0;
while(p)
{
pre = p;
p = p->next;//指针不断向前移动
//printf("cnt = %d\n",cnt);
if(cnt==i) break;
if(p==NULL) break;
cnt++;
}
if(cnt!=i) return 0;
LinkList q = (LinkList)malloc(sizeof(struct LNode));//创建新节点
q->data = e;
pre->next = q;
q->next = p;
return 1;
}