头歌-01链表及其使用

第一题
#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 **********/
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值