在链表指定位置插入结点(链表)
问题描述 :
输入若干(不超过100个)非负整数,创建一个不带头结点的单向链表。
再输入一个位置index以及一个数据data,程序中首先创建一个新结点s,s的数据成员为data,然后调用函数insertNode将s插入到链表的指定位置index处,最后输出结果链表。
请编写insertNode函数,完成插入操作。insertNode函数的原型如下:
struct student *insertNode(struct student *head, struct student *s, int index)
输入说明 :
首先输入若干非负整数,每个整数作为数据放入一个链表结点中,输入-1表示输入结束。
然后输入若干组整数,每组一行,每行包含两个整数,第一个表示需要插入位置index,第二个为新结点的数据。如:输入“1 5”表示在链表的第一个位置(最前面)插入一个结点,结点的数据为5。
输出说明 :
对于每组输入,输出插入结点之后的结果链表。输出的信息以head开头,以tail结尾,以“–>”分隔。具体见输出范例。
如果输入的index超出了链表的范围(如果链表中已有n个结点,则index的有效范围为 1<= index <= n+1),则不插入,输出原链表。如果是空链表,则直接输出“head–>tail”。
输入范例 :
1 2 3 -1
1 10
3 20
输出范例 :
head–>10–>1–>2–>3–>tail
head–>10–>1–>20–>2–>3–>tail
#include <stdio.h>
#include <stdlib.h>
struct student
{
int num;
struct student *next;
};
//从键盘读入数据创建链表,新结点插入到尾部
struct student *createByTail()
{
struct student *head;
struct student *p1,*p2;
int n;
n=0;
p1=p2=(struct student*)malloc(sizeof(struct student));
scanf("%d",&p1->num);
head=NULL; //首先置链表为空链表
while(p1->num!=-1) //num为-1,意味着用户输入结束
{
n=n+1;
if(n==1) //创建第一个结点
head=p1;
else
p2->next=p1;
p2=p1; //p2始终指向最后一个结点(即尾指针)
p1=(struct student*)malloc(sizeof(struct student)); //p1指向新结点
scanf("%d",&p1->num);
}
p2->next=NULL; //最后一个结点的next赋值为NULL
return head;
}
//输出链表中的信息(num)
void displayLink(struct student *head)
{
struct student *p;
p=head;
printf("head-->");
while(p!= NULL)
{
printf("%d-->",p->num);
p=p->next;
}
printf("tail\n");
}
//在链表中第index处插入s指针所指向的结点。index从1开始。
//由于可能插在第一个结点,所以函数返回头指针给主调函数
struct student *insertNode(struct student *head, struct student *s, int index)
{
struct student *p;
p=head;
int len=0;
while(p!=NULL){
len++;
p=p->next;
}
if(index>len+1 || index<=0){//超出长度
return head;
}else{//不超出长度
p=head;
int tag=1;
while(tag!=index){
p=p->next;
tag++;
}
struct student *q;
if(p==head){
s->next=head;
head=s;
}else{
q=head;
while(q->next!=p){
q=q->next;
}
q->next=s;
s->next=p;
}
}
return head;
}
int main()
{
struct student *head;
int index,data;
head=createByTail();
while(scanf("%d%d", &index,&data) != EOF)
{
struct student * s = (struct student *) malloc(sizeof(struct student));
s->num = data;
head=insertNode(head, s, index);
displayLink(head);
}
return 0;
}