标签:break malloc creat and rand void data nod ++
创建链表结构
typedef struct Node
{
int data;
Node *pNext;
}NodeList;
初始化链表节点
Node *InitNode(Node*pNode, int data)
{
pNode = (Node*)malloc(sizeof(Node));
if (pNode == NULL)
return NULL;
pNode->data = data;
pNode->pNext = NULL;
return pNode;
}
创建链表节点
void CreatNode(Node *pHead,int num)
{
Node *pNewNode = NULL;
int i = 0;
srand((int)time(0));
for (i = 0; i < num; i++)
{
pNewNode = (Node*)malloc(sizeof(Node));
if (pNewNode == NULL)
return ;
pNewNode->data = rand() % 100;
pNewNode->pNext = pHead->pNext;
pHead->pNext = pNewNode;
}
}
遍历链表内容:
void PrintNode(Node *pHead)
{
if (pHead == NULL)
cout << "链表为空" << endl;
Node *pTemp = pHead;
while (pTemp)
{
cout << "链表的数据内容:" << pTemp->data << endl;
pTemp = pTemp->pNext;
}
}
//链表节点追加数据内容
Node *InsertNode(Node *pHead, int index,int data)
{
Node *pTemp = pHead;
Node *pNewNode = NULL;
pNewNode = InitNode(pNewNode, data);
if (pTemp->pNext == NULL) //就一个头节点
{
pTemp = pNewNode;
return pHead;
}
while (pTemp != NULL)
{
if (pTemp->data == index)
{
pNewNode->pNext = pTemp->pNext; //先把新节点的指针指向当前节点的下一节点
pTemp->pNext = pNewNode; //再把当前节点的的指针指向新节点
//注意:以上两个顺序不能调换 ,调换会出先死循环
break;
}
else
{
pTemp = pTemp->pNext;
}
}
if (pTemp == NULL)
{
cout << "未找到要你输入的数据节点" << endl;
}
return pHead;
}
//链表节点的删除
Node *DeleteNode(Node *pHead, int data)
{
Node *pTemp = pHead; //用于索引的指针
Node *pRecord = NULL; //用于记录要删除节点的上一节点
if (pTemp->data == data) //要删除的数据在头节点
{
pHead = pTemp->pNext;
free(pTemp);
pHead = NULL;
}
else
{
while (pTemp != NULL)
{
pRecord = pTemp; //记录当前节点
pTemp = pTemp->pNext;
if (pTemp == NULL) //遍历完也没找要删除的节点
{
cout << "遍历完也没找到要删除的数据!" << endl;
return pHead;
}
else if(pTemp->data == data) //找到要删除的数据
{
pRecord->pNext = pTemp->pNext; //删除前把要删除的节点的前一节点的指针指向要删除节点的下一节点
free(pTemp);
break;
}
}
}
return pHead;
}
//main函数调用
int main()
{
Node *pHead = NULL;
pHead = InitNode(pHead, -1);
if (pHead == NULL)
return - 1;
CreatNode(pHead, 10);//创建10个节点 保存随机数据
PrintNode(pHead); //打印节点
//删除节点
int n = 0;
while (n>= 0)
{
//cout << "输入要删除的数据:";
cout << "指定插入数据的位置:";
cin >> n;
//pHead = DeleteNode(pHead, n); //已经测试
pHead = InsertNode(pHead, n, 1000);
PrintNode(pHead);
}
return 0;
}
标签:break malloc creat and rand void data nod ++
原文地址:https://www.cnblogs.com/kevinsharif/p/9107975.html