|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
MyListInsert里面没有开辟新的空间来存放新的节点,ListInsert里面重新开辟了空间来存放新的节点,为什么要开辟新的空间来存数据,没必要?
我写的
- int MyListInsert(Node* pHead, Node* pElem, int index)
- {
- Node* pCurrentNode = pHead;
- Node* temp = NULL;
- int length = ListLength2(pHead);
- if (index > 0 && index <= length)
- {
- for (int i = 0; i < length; i++)
- {
- if (i + 1 == index)
- {
- temp = pCurrentNode->pNext;
- pCurrentNode = pElem;
- pElem->pNext = temp;
- return 1;
- break;
- }
- else
- {
- pCurrentNode = pCurrentNode->pNext;
- }
- }
- }
- else
- {
- printf("!!!!index out the range of the array\n");
- return 0;
- }
-
- }
复制代码
老师i写的:
- int ListInsert(Node* pHead, Node* pElem, int index)
- {
- int length = ListLength2(pHead);
- if (index < 0 || index > length)
- {
- return 0;
- }
- //开辟空间,你不能直接将传进来的节点内存直接插入链表,这里
- Node* pNode = (Node*)malloc(sizeof(Node));
- strcpy_s(pNode->name, pElem->name);
- strcpy_s(pNode->phone, pElem->phone);
- if (pNode == NULL)
- {
- return 0;
- }
- Node* pCurrentNode = pHead;
- int count = 0;
- Node* temp = NULL;
- while (pCurrentNode != NULL)
- {
- if (count == index)
- {
- temp = pCurrentNode->pNext;
- pCurrentNode = pNode;
- pNode->pNext = temp;
- return 1;
- }
- count++;
- pCurrentNode = pCurrentNode->pNext;
- }
- }
复制代码
|
|