C 插入结点 填空题
我被绕晕了,4)乱填的,需要一个详细的解答
3. 设指针p指向单链表中结点A,指针s指向被插入的结点X,则在结点A的前面插入结点X时的操作序列为:
1) s->next=___A_______;2) p->next=s;3)t=p->data;
4) p->data=___s_______;5) s->data=t; {:301_1009:}我也等等答案 本帖最后由 古月不傲 于 2020-2-23 01:10 编辑
#include <iostream>
using namespace std;
typedef struct _List
{
struct _List *pNext;
int nData;
}List, *pList;
pList CreateHeader()
{
pList plist = new List;
memset(plist, 0, sizeof(List));
plist->pNext = NULL;
plist->nData = 0;
return plist;
}
void InsertEnd(pList *plist, int nData)
{
pList pNew = new List;
memset(pNew, 0, sizeof(List));
pList pTemp = *plist;
if ((*plist)->pNext == NULL)
{
(*plist)->pNext = pNew;
pNew->pNext = NULL;
pNew->nData = nData;
return;
}
while (pTemp->pNext != NULL)
{
pTemp = pTemp->pNext;
}
pTemp->pNext = pNew;
pNew->pNext = NULL;
pNew->nData = nData;
}
void InsertAny(pList *plist, int nData, int nPos)
{
pList pTemp = *plist;
int i = 0;
while (pTemp->pNext != NULL && i <= nPos - 1)
{
pTemp = pTemp->pNext;
i++;
}
pList pNew = new List;
memset(pNew, 0, sizeof(List));
pNew->pNext = pTemp->pNext;
pTemp->pNext = pNew;
pNew->nData = nData;
}
void Print(pList *plist)
{
pList pTemp = *plist;
while (pTemp->pNext != NULL)
{
printf("地址:%x 值%d\n", pTemp->pNext, pTemp->pNext->nData);
pTemp = pTemp->pNext;
}
}
int main(void)
{
pList plist;
plist = CreateHeader();
InsertEnd(&plist, 2);
InsertEnd(&plist, 4);
InsertEnd(&plist, 6);
InsertEnd(&plist, 7);
InsertEnd(&plist, 10);
InsertEnd(&plist, 3);
Print(&plist);
system("cls");
InsertAny(&plist, 5, 2);
Print(&plist);
system("pause");
return 0;
}
本帖最后由 古月不傲 于 2020-2-23 01:25 编辑
链表操作通过节点遍历找到下一个节点
所以s->next = A是不对的 这样是找不到的
s->next = p->next;
p->data = s->data;
这题目我都看的晕咯 就这样吧 管他对错了{:1_918:} 你要弄明白头插法和尾插法,个人建议是画图 luanshils 发表于 2020-2-23 01:30
你要弄明白头插法和尾插法,个人建议是画图
知道的,链栈只能头插法 ing 发表于 2020-2-23 14:41
知道的,链栈只能头插法
那确实,只能压栈 这个题的思路应该是在A后面插入X然后交换A,X的值。间接上实现头插。所以答案应该是A->next 和x.data
页:
[1]