truct MyList
{
int nA;
MyList* pTnext;
MyList* pTpre;
};
//双向链表的生成
MyList* CreateList()
{
MyList* pHead = NULL;
MyList* pPre = NULL;
MyList* pNext = NULL;
MyList* pCur = NULL;
int nA = 0;
printf("请输入您的数字");
for (int i = 0;i < 5;i++)
{
scanf_s("%d", &nA);
pCur = new MyList;
pCur->pTpre = pPre;
pCur->pTnext = NULL;
if (pCur != nullptr)
{
pCur->nA = nA;
}
if (pPre == NULL)
{
pHead = pCur;
}
else
{
pPre->pTnext = pCur;
}
pPre = pCur;
}
return pHead;
}
//第一种交换结点的值
MyList* ListWord(MyList* pList)
{
MyList* pCur = pList;
int nB = 0;
while (pCur != NULL)
{
printf("%d\n", pCur->nA);
nB = nB + 1;
pCur = pCur->pTnext;
}
pCur = pList;//重新赋值不然下面执行有错
for (int i=0;i<nB;i++)
{
for (int j=0;j<nB;j++)
{
if (pCur->pTnext != NULL)
{
if (pCur->nA > pCur->pTnext->nA)
{
int temp = pCur->nA;
pCur->nA = pCur->pTnext->nA;
pCur->pTnext->nA = temp;
}
else
{
}
pCur = pCur->pTnext;
}
}
pCur = pList;
}
return pList;
}
//第二种结点值的交换
MyList* ListTextTwo(MyList* pListtwo)
{
MyList* pCur = pListtwo;
MyList* pTemp = pListtwo;
int nB = 0;
int nC = 0;
pCur = pListtwo;
if (pListtwo == NULL)
{
return pListtwo;
}
MyList* pCurBig = pListtwo;
while (pCurBig != NULL)
{
//每次进来从头开始比较
pCur = pListtwo;
while (pCur != NULL && pCur->pTnext != NULL)
{
if (pCur->nA > pCur->pTnext->nA)
{
int temp = pCur->nA;
pCur->nA = pCur->pTnext->nA;
pCur->pTnext->nA = temp;
}
pCur = pCur->pTnext;
}
pCurBig = pCurBig->pTnext;
}
return pListtwo;
}
//交换结点
MyList* ListRandTwo(MyList* pListTwo)
{
MyList* pCur = pListTwo;
MyList* pHead = pListTwo;
MyList* pA;
MyList* pB;
MyList* pC;
MyList* pD;
pA = NULL;
pB = pCur;
if (pB == nullptr)
{
return pListTwo;
}
pC = pB->pTnext;
pD = NULL;
int nB = 0;
while (pCur)
{
printf("%d\n", pCur->nA);
pCur = pCur->pTnext;
nB = nB + 1;
}
for (int i=0;i<nB;i++)
{
pCur = pListTwo;
while (pCur != NULL && pCur->pTnext != NULL)
{
pA = pCur->pTpre;
pB = pCur;
pC = pCur->pTnext;
if (pC != nullptr)
{
pD = pC->pTnext;
}
else
{
break;
}
if (pA->nA > pC->nA)
{
//连接
pC->pTnext = pB;
pC->pTpre = pA;
pB->pTnext = pD;
pD->pTpre = pB;
if (pA != nullptr)
{
pA->pTnext = pC;
}
else
{
pListTwo = pC;
}
if (pD != NULL)
{
pD->pTpre = pB;
}
}
else
{
pCur = pCur->pTnext;
}
}
}
return pListTwo;
}
int main()
{
int nA = 123;
int nB = 888;
int nC = 234;
int nD = 555;
MyList* pList = CreateList();//测试过了pList值是有的
ListTextTwo(pList);
ListTextTwo(pList);
ListWord(pList);