有关带头结点的单链表的基本操作

带头结点的链表:创建(头插法)、输出、查找、插入(差后面)、删除

  • 关于创建:
    头指针的创建提供了便利,不必考虑创建第一个结点的特殊情况
    头插法较尾插法在链表创建中更为标准(雾),可以不用定义指针pta指向尾结点;
    注意头结点的定义在create函数中哦

  • 关于遍历(输出)
    先将p=p->next以跳过头结点从第一个结点开始输出

  • 关于查找
    该部分有无头指针差别不大(甚至可以根本没有差别)

  • 关于插入
    普遍的插入规则是插入到指定结点的后一个(好像也有前一个的吧?),那么要把插入的变为第一个结点就要插在头指针后面,可以把头指针的信息域赋值,这样就可以查找啦。不必考虑第一个结点的特殊情况

  • 关于删除
    不必考虑第一个结点的特殊情况,还是挺简单的吧

#include<stdio.h>
struct student//定义结构体
{
 int num;//信息域
 float score;
 struct student *next;//指针域
};
struct student * create() //建立链表 返回值为结构体指针 头插法
{
 int num;
 float score;
 struct student *ph, *pte;//无需建立尾节点对应指针,若是尾插法则需要
 ph = (struct student *)malloc(sizeof(struct student));//注意也要为头结点申请空间
 ph->next = NULL;///头结点的指针域为初始化NULL
 ph->num = -1;
 scanf("%d%f", &num, &score);
 while (score >= 0)//无需单独考虑第一个结点的情况
 {
  pte = (struct student *)malloc(sizeof(struct student));
  pte->num = num;pte->score = score;
  pte->next =ph->next;//若为第一个结点pte->next指向NULL,若不是则指向原第一个结点//接后面
  ph->next = pte;//接前面
  scanf("%d%f", &num, &score);
 }
 return ph;
}
void list(struct student *p)//输出链表 无返回值 形参为头指针
{
 p = p->next;//跳过头结点
 while (p)
 {
  printf("%d      %f\n", p->num, p->score);
  p =p ->next;
 }
}
struct student * search(struct student *p, float s)//结点查找,按分数找学号,返回找到的结点的地址 ,并输出p->name
{
 while (p)
 {
  if (p->score == s)//找到了就跳出循环并返回此时的p
   break;
  p = p->next;
 }
 return p;//如果没找到,则p最后为NULL,循环结束
}
struct student * ins(struct student *p, int ns, int n, float s)//插入结点在ns之后
{
 struct student *pt;
 struct student *ph = p;
 pt = (struct student *)malloc(sizeof(struct student));
 pt->num = n;pt->score = s;pt->next = NULL;
 while (p)//找到结点ns并使p指向它
 {
  if (p->num == ns)
   break;
  p = p->next;
 }//可插在链表的任何位置
  pt->next = p->next;//接后面
  p->next = pt;//接前面
 return ph;
}
struct student * del(struct student *p, int n)//删除结点 返回值为结构体指针即修改过的头指针 传入原头指针和name
{
 struct student *pre = p;//定义pre临时,记录要删除结点的地址
 struct student *ph = p;//定义ph用于返回
 while (p)//遍历链表 
 {
  if (p->num == n)//找到啦,跳出循环,p指向要删除的结点
   break;
  pre = p;//pre就指向了要删除的那个结点之前
  p = p->next;//p就指向下一个
 }
 pre->next = p->next;//找到之后呢,让这个结点之前pre的next指向改结点的next
 free(p);//然后释放这个结点
 return ph;
}
int main()
{
 struct student *ph,*pt;
 printf("创建:输入score<0以结束链表创建\n");
 ph = create();
 list(ph);
 //
 printf("查找:输入score以查找对应num\n");
 float s1;
 scanf("%f", &s1);
 pt = search(ph, s1);//
 if (pt)//找到了,此时pt非空
  printf("%d\n", pt->num);//输出其指向的num
 else
  printf("NONE\n");
 //
 int ns, n;
 float s;
 printf("插入:输入num=-1以将结点设置为第一个\n");
 scanf("%d%d%f", &ns, &n, &s);
 ph = ins(ph, ns, n, s);
 list(ph);
 //
 printf("删除:输入要删除的num");
 int n1;
 scanf("%d", &n1);
 ph = del(ph, n1);//传入头指针和要删除的num,将更改过的头指针传给ph
 list(ph);
 //
 getchar();getchar();
 return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_43432875/article/details/85036486