头歌-01链表及其使用

作者:@什么时候才能不困
本文为作者原创,转载请注明出处:https://www.cnblogs.com/haggard/p/17727132.html


第一题

#include "linearList.h"

node *insertTail(node *h, node *t)
{
    // 请在此添加代码,补全函数insertTail
    /********** Begin *********/
    if(h==NULL)
    {
        t->next=NULL;
        return t;
    }
    node *p=h;
    while(p->next)
    {
        p=p->next;
    }     
     p->next=t;
       t->next=NULL;
        return h;
    /********** End **********/
}

 

第二题
 #include "linearList.h"

node * insertHead(node *h, node *t)
{
    // 请在此添加代码,补全函数insertHead
    /********** Begin *********/
    t->next=h;
    return t;
    /********** End **********/
}

 

第三题
 #include "linearList.h"

node * search(node * h, int num)
{
    // 请在此添加代码,补全函数search
    /********** Begin *********/
while(h)
    {// h为真,即h指向的结点存在
        if(h->data == num)
        {
              return h;
        } 
        h = h->next;  // 将该结点的指针域赋值给h,h就指向了下一个结点
    }
    return NULL; 
    /********** End **********/
}

 

第四题
 #include "linearList.h"

node * delAt(node * h, int i)
{
    // 请在此添加代码,补全函数delAt
    /********** Begin *********/
    if(i<0) //序号非法,不删除
 {
  return h;
 }
 node *p=NULL, *q = h; // 定位删除结点,试图让q指向要删除结点,p指向其前面的结点
 for(int k=0;k<i;k++)
 {
  if(q->next==NULL) //后面没有结点了,序号非法
   return h;
  p=q;
  q=q->next;
 }
 if(p) //p指向的结点存在,不是删除首结点
 {
  //删除q指向的结点,让p指向结点的指针域指向q的后续结点
  p->next = q->next;
  //释放空间
  delete q;
  return h;
 }
 else //删除首结点
 {
  h = q->next; //下一个结点成了首结点
  //释放空间
  delete q;
  return h;
 }
    /********** End **********/
}

 

第五题
 #include "linearList.h"

node * delHas(node * h, int n)
{
    // 请在此添加代码,补全函数delHas
    /********** Begin *********/
     node *p = NULL, *q = h;  // p为要删除结点的前结点,q指向要删除结点
    while(q)
    {// h为真,即h指向的结点存在
        if(q->data == n)
            break; // 找到了
        if(q->next == NULL)  // 后面没有结点了,没有结点满足条件
            return h;  // 不删除,直接返回
        // 继续往后找,两个指针一起后移
        p = q;
        q = q->next;
    }
    // 删除q指向的结点
    if(p == NULL)  // 删除头结点
    {
        h = q->next;  // 下一个结点变成头结点
        delete q;  // 删除结点
        return h;
    }
    // 不是头结点
    p->next = q->next;  // 把q指向结点的指针域(q后面结点的地址)赋值给p指向结点的指针域
    return h;
    /********** End **********/
}

 

第六题
 #include "linearList.h"

int listLength(node * h)
{
    // 请在此添加代码,补全函数listLength
    /********** Begin *********/
    int n = 0;
    while(h)
    {
        n++;
        h = h->next;
    }
    return n;

    /********** End **********/
}
posted @   什么时候才能不困  阅读(72)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
// /* */
点击右上角即可分享
微信分享提示