zoukankan      html  css  js  c++  java
  • 链表的删除

    函数deletelist从以head为头指针的链表中删除成绩低于min_score的学生,并返回结果链表的头指针。

     1 struct stud_node *deletelist( struct stud_node *head, int min_score ) {
     2     //删除成绩低于min_score的学生
     3     struct stud_node *p, *q;
     4     while (head && head->score<min_score) {
     5         q = head;
     6         head = head->next;
     7         free(q);
     8     }
     9     if ( head == NULL ){  //为防止head->next为空, 即只有链表只有一个元素的情况
    10         return NULL;
    11     } 
    12     p = head;
    13     q = head->next;
    14     while ( q ){  //如果q不是空
    15         if ( q->score<min_score ){  //如果q指向的score小于
    16             p->next = q->next;  //令p->next(即head->next) = q->next
    17             free(q);
    18         }
    19         else {
    20             p = q;  //若没有符合的元素, p指针往后移一位
    21         }
    22         q = p->next;  //q指针一定位于p->next
    23     }
    24     return head;
    25 }

    一样要struct stud_node *p, *q, *head(存放了整个链表的指针);

    一开始, 先判断head的元素是不是要找的元素, 如果是, 做一个指针赋值, free掉此元素

    如果head不是要找的元素, 让p = head, q = head->next; 由这两个指针操纵位置和删除;

    照例画图理解会好一点

  • 相关阅读:
    bzoj4554: [Tjoi2016&Heoi2016]游戏
    bzoj3166: [Heoi2013]Alo
    luogu3398 仓鼠找sugar
    bzoj3261: 最大异或和
    bzoj3446: [Usaco2014 Feb]Cow Decathlon
    BZOJ1742[Usaco2005 nov]Grazing on the Run 边跑边吃草
    bzoj2750: [HAOI2012]Road
    bzoj4448: [Scoi2015]情报传递
    bzoj2809: [Apio2012]dispatching
    bzoj 1452
  • 原文地址:https://www.cnblogs.com/zhengxin909/p/12001413.html
Copyright © 2011-2022 走看看