删除链表第index个结点
问题描述 :
输入若干(不超过100个)非负整数,创建一个不带头结点的单向链表。在输入一个位置index,从链表中删除第index个结点,输出结果链表。
请编写deleteNode函数,完成删除操作。deleteNode函数的原型如下:
struct student *deleteNode(struct student *head,int index)
输入说明 :
首先输入若干非负整数,每个整数作为数据放入一个链表结点中,输入-1表示输入结束。
然后输入若干组整数,每组一行,每行仅包含一个整数,表示需要删除的结点的位置index。如:输入1表示删除链表的第一个(最前面一个)结点。
输出说明 :
对于每组输入,输出删除第index个结点之后的结果链表。输出的信息以head开头,以tail结尾,以“–>”分隔。具体见输出范例。
如果输入的index超出了链表的范围,则不删除,输出原链表。如果是空链表,则直接输出“head–>tail”。
输入范例 :
1000 2342 8883 -1
4
3
1
1
输出范例 :
head–>1000–>2342–>8883–>tail
head–>1000–>2342–>tail
head–>2342–>tail
head–>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个结点。index从1开始。
//由于可能删除第一个结点,所以函数返回头指针给主调函数
struct student *deleteNode(struct student *head,int index)
{
struct student *p;
p=head;
int len=0;
while(p!=NULL){
len++;
p=p->next;
}
if(index>len || index<=0){//超出长度
return head;
}else{//不超出长度
p=head;
int tag=1;
while(tag!=index){
tag++;
p=p->next;
}
struct student *q;
if(p==head){
head=p->next;
}else{
q=head;
while(q->next!=p){
q=q->next;
}
q->next=p->next;
}
delete p;
}
return head;
}
int main()
{
struct student *head;
int index;
head=createByTail();
while(scanf("%d", &index) != -1)
{
head=deleteNode(head, index);
displayLink(head);
}
}