-
-
Save liuqinh2s/496cf7d2d396545b33f79b65ef80e1c7 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include<iostream> | |
#include<stack> | |
using namespace std; | |
struct ListNode{ | |
int value; | |
ListNode* pNext; | |
}; | |
void reverse(ListNode** pHead){ | |
if(pHead==NULL || *pHead==NULL || (*pHead)->pNext==NULL){ | |
return; | |
} | |
ListNode* pNode1 = *pHead; | |
ListNode* pNode2 = (*pHead)->pNext; | |
while(pNode1!=NULL && pNode2!=NULL){ | |
ListNode* pTempNode = pNode2->pNext; | |
pNode2->pNext = pNode1; | |
pNode1 = pNode2; | |
pNode2 = pTempNode; | |
} | |
(*pHead)->pNext = NULL; | |
*pHead = pNode1; | |
} | |
void printList(ListNode* pHead){ | |
ListNode* pNode = pHead; | |
while(pNode!=NULL){ | |
cout << pNode->value << endl; | |
pNode = pNode->pNext; | |
} | |
} | |
void reversePrintList(ListNode* pHead){ | |
stack<int> stack; | |
ListNode* pNode = pHead; | |
while(pNode!=NULL){ | |
stack.push(pNode->value); | |
pNode = pNode->pNext; | |
} | |
while(!stack.empty()){ | |
cout << stack.top() << endl; | |
stack.pop(); | |
} | |
} | |
void recursePrintList(ListNode* pHead){ | |
if(pHead==NULL){ | |
return; | |
} | |
recursePrintList(pHead->pNext); | |
cout << pHead->value << endl; | |
} | |
void addToTail(ListNode** pHead, int value){ | |
ListNode* pNew = new ListNode(); | |
pNew->value = value; | |
pNew->pNext = NULL; | |
if(*pHead==NULL){ | |
*pHead = pNew; | |
}else{ | |
ListNode* pNode = *pHead; | |
while(pNode->pNext!=NULL){ | |
pNode = pNode->pNext; | |
} | |
pNode->pNext = pNew; | |
} | |
} | |
void removeNode(ListNode** pHead, int value){ | |
if(pHead==NULL || *pHead==NULL){ | |
return; | |
} | |
ListNode* pNode = *pHead; | |
if((*pHead)->value == value){ | |
*pHead = (*pHead)->pNext; | |
delete pNode; | |
}else{ | |
while(pNode->pNext!=NULL && pNode->pNext->value!=value){ | |
pNode = pNode->pNext; | |
} | |
if(pNode->pNext!=NULL){ | |
ListNode* pTempNode = pNode->pNext; | |
pNode->pNext = pNode->pNext->pNext; | |
delete pTempNode; | |
} | |
} | |
} | |
int main(){ | |
ListNode* pHead = NULL; | |
for(int i=0;i<10;i++){ | |
addToTail(&pHead, i); | |
} | |
// printList(pHead); | |
// reverse(&pHead); | |
// printList(pHead); | |
reversePrintList(pHead); | |
// recursePrintList(pHead); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment