#include<bits/stdc++.h>
using namespace std;
struct ListNode{
int m_Value;
ListNode* m_Next;
};
//删除链表中某个节点
void RemoveNode(ListNode** pHead,int value)
{
if(pHead==nullptr||*pHead==nullptr) return;
//比较头结点特殊情况
if((*pHead)->m_Value==value)
{
if((*pHead)->m_Next!=nullptr) {
(*pHead) = (*pHead)->m_Next;
}
else {
delete pHead; //释放了堆空间,但是并没有释放指针所占的内存,只是它变成了空指针而已
(*pHead) = nullptr;
}
}
else {
ListNode* pNode = (*pHead);
pNode = pNode->m_Next;
ListNode* preNode = (*pHead);
while(pNode->m_Value!=value)
{
if(pNode->m_Next!=nullptr) {
preNode = pNode;
pNode = pNode->m_Next;
}
else break;
}
preNode->m_Next = pNode->m_Next;
}
}
//在链表末尾添加节点
void AddToTail(ListNode** pHead,int value)
{
ListNode* newNode = new ListNode();
newNode->m_Next = nullptr;
newNode->m_Value = value;
if(*pHead==nullptr)
{
(*pHead) = newNode;
}
else {
ListNode* pNode = *pHead;
while(pNode->m_Next != nullptr)
{
pNode = pNode ->m_Next;
}
pNode->m_Next = newNode;
}
}
int main()
{
ListNode* pHead = new ListNode();
pHead->m_Next = nullptr;
pHead->m_Value = 1;
AddToTail(&pHead,2);
AddToTail(&pHead,3);
AddToTail(&pHead,4);
ListNode* pNode = pHead;
//输出链表中的节点信息
while(true)
{
printf("%d ",pNode->m_Value);
if(pNode->m_Next!=nullptr) pNode = pNode->m_Next;
else break;
}
printf("\n");
RemoveNode(&pHead,1);
RemoveNode(&pHead,3);
pNode = pHead;
while(true)
{
printf("%d ",pNode->m_Value);
if(pNode->m_Next!=nullptr) pNode = pNode->m_Next;
else break;
}
printf("\n");
delete pHead;
return 0;
}
从尾到头打印链表:
//从尾到头打印链表,使用栈来实现
#include<bits/stdc++.h>
using namespace std;
struct ListNode{
int m_Value;
ListNode* m_Next;
};
void AddToTail(ListNode** pHead,int value)
{
ListNode* pNew = new ListNode();
pNew->m_Next = nullptr;
pNew->m_Value = value;
if(*pHead==nullptr) {
(*pHead) = pNew;
}
else {
ListNode* pNode = (*pHead);
while(pNode->m_Next!=nullptr)
{
pNode = pNode->m_Next;
}
pNode->m_Next = pNew;
}
}
int main()
{
// int k = 3; 指针赋值,把地址传递给另一个指针
// int* k1 = &k;
// int* k2 = k1;
// *k2 = 4;
// cout<<k<<endl;
ListNode* pHead = nullptr;
int n;
scanf("%d",&n);
for(int i=0;i<n;i++)
{
int k;
scanf("%d",&k);
AddToTail(&pHead,k);
}
//遍历链表
printf("遍历链表\n");
ListNode* pNode = pHead;
while(true)
{
printf("%d ",pNode->m_Value);
if(pNode->m_Next!=nullptr) pNode = pNode->m_Next;
else break;
}
printf("\n");
//翻转链表
printf("翻转链表\n");
stack<int>str;
while(!str.empty()) str.pop();
pNode = pHead;
while(true)
{
str.push(pNode->m_Value);
if(pNode->m_Next!=nullptr) pNode = pNode->m_Next;
else break;
}
while(!str.empty())
{
printf("%d ",str.top());
str.pop();
}
delete pHead;
return 0;
}