涉及内容,单链表的构建,反转,打印
struct ListNode
{
int value;
ListNode* pNext;
};
//在尾部插入新元素
void AddToTail(ListNode* pFirst, int value)
{
ListNode* newNode = new ListNode;
newNode->value = value;
newNode->pNext = nullptr;
if (pFirst == nullptr)
{
pFirst = newNode;
}
else
{
ListNode* pHead = pFirst;
while (pHead->pNext != nullptr)
{
pHead = pHead->pNext;
}
pHead->pNext = newNode;
}
}
//打印链表中的元素
void PrintList(ListNode* pHead)
{
if (pHead == nullptr)
{
return;
}
cout << "---------------------------list------------------- \n";
// 通过函数传参的方式将头结点的地址给phead 。等价于ListNode* pHead = one;
// 通过pHead依次访问每个节点,one节点的地址并不会改变
while (pHead != nullptr)
{
cout << (void*)pHead << ":" << pHead->value << " next: " << (void*)pHead->pNext << endl;
pHead = pHead->pNext;
}
}
//移除链表中的某一节点 有问题
void RemoveOne(ListNode *pHead,int target)
{
if (pHead == nullptr)
{
return;
}
cout << "fun :" << pHead << endl;
cout << "*fun :" << pHead <<endl;
ListNode* pTmp = pHead;
// 若待删除的节点为第一个,则在返回值为void 时 ,无法实现。
if (pTmp->value == target)
{
pHead = pTmp->pNext;
return;
}
while (pTmp->pNext != nullptr)
{
cout << "value :" << pTmp->value << endl;
if (pTmp->pNext->value == target) //第二个节点
{
pTmp->pNext = pTmp->pNext->pNext;
// pTmp->pNext = nullptr;
break;
}
pTmp = pTmp->pNext;
}
}
//移除链表中的某一个节点,Ok版
ListNode* RemoveOneOk(ListNode* pHead, int target)
{
if (pHead == nullptr)
{
return pHead;
}
cout << "fun :" << pHead << endl;
cout << "*fun :" << pHead << endl;
ListNode* pTmp = pHead;
// 若待删除的节点为第一个,则在返回值为void 时 ,无法实现。
if (pTmp->value == target)
{
pHead = pTmp->pNext;
return pHead;
}
while (pTmp->pNext != nullptr)
{
cout << "value :" << pTmp->value << endl;
if (pTmp->pNext->value == target) //第二个节点
{
pTmp->pNext = pTmp->pNext->pNext;
break;
}
pTmp = pTmp->pNext;
}
return pHead;
}
ListNode* ReverseList(ListNode* pHead)
{
//只有一个元素 或者没有元素返回原链表
if (pHead == nullptr || pHead->pNext == nullptr)
return pHead;
ListNode* newHead = nullptr;
//新链表的尾结点
ListNode* nextHead = pHead; //旧链表待反序的节点的首节点
ListNode* tmp = pHead; //临时变量,保存剩余的节点list
while (nextHead != nullptr)
{
tmp = nextHead->pNext; //保存节点的位置,方便循环 得到剩余节点的第一个节点。
nextHead->pNext = newHead; //第一次。将第一个节点的next变为nullptr 之后为上一个节点
newHead = nextHead; //更新反转后链表的头结点
nextHead = tmp;
}
return newHead;
}
void test(int* pv)
{
//*pv = 50;
cout << "&pv adress : " << &pv << endl;
cout << "pv : " << pv << endl;
cout << "*pv : " << *pv << endl;
int c = 100;
cout << "&c : " << &c << endl;
pv = &c;
cout << "pv : " << pv << endl;
cout << "*pv : " << *pv << endl;
}
int main()
{
ListNode* one = new ListNode;
one->value = 2;
one->pNext = nullptr;
cout << "& head address :" << &one << endl;
cout << " head address :" << one << endl;
AddToTail(one, 3);
AddToTail(one, 4);
AddToTail(one, 5);
AddToTail(one, 6);
AddToTail(one, 7);
PrintList(one);
one = RemoveOneOk(one, 7);
PrintList(one);
cout << "+++++++++++++++++++++++++++++++++++++\n";
one = ReverseList(one);
PrintList(one);
}