#if 1
#include <stdio.h>
#include <stdlib.h>
struct Student {
int num;
float score;
struct Student* next;
};
void output(struct Student* head);
int main() {
struct Student* head = NULL,*prep = NULL;
struct Student* node,*tail = NULL;
struct Student* p;
enum direction { left=-1,right=1}dire;//1 代表从正方向,也就是尾巴开始插入
int i,j,length;
int del_case,location;//删除节点的方式
double value;//要删除的数值
double a;
/*printf("please input the direction that you want to insert!\n");//选择插入方向
scanf_s("%d", &dire);*/
scanf_s("%lf", &a);
//node = (struct Student*)malloc(sizeof(struct Student));
//node->num = 001;
//node->score = 89.5 ;
//node->next = NULL;//动态创建一个节点,并且赋值,指向空
//head = node;//节点给头
//tail = node;
length = 0;
j = 0;
//下面的代码段插入节点
do {
node = (struct Student*)malloc(sizeof(struct Student));
node->score = a;
node->next = NULL;//动态创建一个节点,并且赋值,指向空
length++;
if (head==NULL)
{
head = node;
tail = node;
prep = node;
}
else
{
p = head;
if (node->score > tail->score)//比最后一个节点的值还大的话,就直接插入到尾部,????(是为什么这个判断很重要,但是下面那个判断不重要)
{
tail->next = node;//先移动指向
tail = node;
}
else if(node->score < head->score)
{
node->next = head;//当前的头成为新插入的节点的next
head = node;
}
else
{
//printf("tail-1 = %lf,tail = %lf\n", p->score, tail->score);
//(tail - 1)->next = node;//看来结构体指针不能使用加减号,得单独定义一个前指针和后指针
//node->next = tail;
while (node->score > p->score)
{
prep = p;
p = p->next;
}
prep->next = node;
node->next = p;
}
//if (dire==right)//无序插入节点,主要是区分插入方向
//{
// tail->next = node;//先移动指向
// tail = node;
//}
//else
//{
// node->next = head;//当前的头成为新插入的节点的next
// head = node;//新插入的节点成为头结点
//}
}
scanf_s("%lf", &a);
} while (a != 0);
printf("please input the way you want to delte,case 1 means delete location\n");
scanf_s("%d", &del_case);
//下面的代码段删除节点,分为两种,一种是删除固定编号位置处的节点,一种是删除某个读入的数值
switch (del_case)
{
case 1:
printf("please input the location you want you delete:\n");
scanf_s("%d", &location);
if (location> length)
{
printf("not exist this location\n");
break;
}
else
{
p = head;
prep = head;
if (location == 1)
{
head = head->next;
}
else
{
for (i = 1; i < location; i++)
{
prep = p;
p = p->next;//已经到了指定位置了
}
prep->next = p->next;
delete p;
}
}
break;
case 2:
printf("please input the value you want you delete:\n");
scanf_s("%lf", &value);
p = head;
prep = p;
while (true)
{
if (p->score == value)
{
if (p==head)
{
head = head->next;
}
else
{
prep->next = p->next;
delete p;
}
break;
}
else
{
prep = p;
p = p->next;
}
}
break;
}
//node = (struct Student*)malloc(sizeof(struct Student));
//node->num = 002;
//node->score = 90;
//node->next = NULL;//同上一个节点的创建方式,重新创了一个节点
//head->next = node;//节点给头的next
//node = (struct Student*)malloc(sizeof(struct Student));
//node->num = 003;
//node->score = 85;
//node->next = NULL;
//head->next->next = node;
output(head);//传入头指针,进行链表打印
return 0;
}
void output(struct Student* head)
{
struct Student* p;
p = head;//
do {//使用函数,参数是链表头
printf("%5.1f\n", p->score);
p = p->next;
} while (p != NULL);
}
#endif
删除链表的指定位置、指定数值的结点
最新推荐文章于 2024-03-11 16:17:14 发布