鱼C论坛

 找回密码
 立即注册
查看: 626|回复: 0

为什么下列子函数实现单链表 在指定位置插入元素,不能像下面这么做

[复制链接]
发表于 2022-3-23 22:28:46 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
MyListInsert里面没有开辟新的空间来存放新的节点,ListInsert里面重新开辟了空间来存放新的节点,为什么要开辟新的空间来存数据,没必要?

我写的

  1. int MyListInsert(Node* pHead, Node* pElem, int index)
  2. {
  3.         Node* pCurrentNode = pHead;
  4.         Node* temp = NULL;
  5.         int length = ListLength2(pHead);
  6.         if (index > 0 && index <= length)
  7.         {
  8.                 for (int i = 0; i < length; i++)
  9.                 {
  10.                         if (i + 1 == index)
  11.                         {
  12.                                 temp = pCurrentNode->pNext;
  13.                                 pCurrentNode = pElem;
  14.                                 pElem->pNext = temp;
  15.                                 return 1;
  16.                                 break;
  17.                         }
  18.                         else
  19.                         {
  20.                                 pCurrentNode = pCurrentNode->pNext;
  21.                         }
  22.                 }
  23.         }
  24.         else
  25.         {
  26.                 printf("!!!!index out the range of the array\n");
  27.                 return 0;
  28.         }
  29.        
  30. }
复制代码


老师i写的:
  1. int ListInsert(Node* pHead, Node* pElem, int index)
  2. {
  3.         int length = ListLength2(pHead);
  4.         if (index < 0 || index > length)
  5.         {
  6.                 return 0;
  7.         }

  8.         //开辟空间,你不能直接将传进来的节点内存直接插入链表,这里
  9.         Node* pNode = (Node*)malloc(sizeof(Node));
  10.         strcpy_s(pNode->name, pElem->name);
  11.         strcpy_s(pNode->phone, pElem->phone);

  12.         if (pNode == NULL)
  13.         {
  14.                 return 0;
  15.         }
  16.         Node* pCurrentNode = pHead;

  17.         int count = 0;
  18.         Node* temp = NULL;
  19.         while (pCurrentNode != NULL)
  20.         {
  21.                 if (count == index)
  22.                 {
  23.                         temp = pCurrentNode->pNext;
  24.                         pCurrentNode = pNode;
  25.                         pNode->pNext = temp;
  26.                         return 1;
  27.                 }
  28.                 count++;
  29.                 pCurrentNode = pCurrentNode->pNext;
  30.         }

  31. }
复制代码

想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2024-5-22 07:05

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表