單項鍊表操作
阿新 • • 發佈:2018-11-14
using namespace std; struct ListNode{ int dat; ListNode* next; }; ListNode * head = NULL; ListNode * createNode(void) { ListNode * newNode = (ListNode*)malloc(sizeof(ListNode) * 1); return newNode; } void addList(int data) { ListNode * pList = head; if(pList == NULL) { head = createNode(); head->dat = data; head->next = NULL; return; } //find the end node while(pList->next != NULL) { pList = pList->next; } pList->next = createNode(); pList = pList->next; pList->dat = data; pList->next = NULL; } void printList(void) { ListNode * pList = head; if(pList == NULL) { cout<<"List is NULL"<<endl; return; } //find the end node while(pList != NULL) { cout<<pList->dat<<endl; pList = pList->next; } } void delList(void) { ListNode * pList = head; if(pList == NULL) { cout<<"List is NULL, No list node to del... "<<endl; return; } //find the end node while(pList != NULL) { head = pList->next; cout<<"del "<<pList->dat<<endl; free(pList); pList = head; } } void delListHead(ListNode* phead) { ListNode * pList = phead; cout<<"phead==0x08x "<<phead->next<<endl; cout<<"&phead==0x08x "<<&phead<<endl; cout<<"head==0x08x "<<head->next<<endl; cout<<"&head==0x08x "<<&head<<endl; if(pList == NULL) { cout<<"List is NULL, No list node to del... "<<endl; return; } } void RevList(ListNode* pHead) { ListNode * pTemp = NULL; ListNode * pNewHead = NULL; if(pHead == NULL) { cout<<"List is NULL, Rev finish... "<<endl; return; } #if 0 if(pHead->next == NULL) { cout<<"one node only, Rev finish... "<<endl; return; } #endif //find the end node while(pHead != NULL) { //get one node from list and reset list head point to the next node pTemp = pHead; pHead = pHead->next; cout<<"del "<<pTemp->dat<<" from old list"; //set new node next is newhead and reset new head pTemp->next = pNewHead; pNewHead = pTemp; cout<<" add to new list"<<endl; } head = pNewHead; } void RevListParaPP(ListNode** ppHead) { ListNode * pHead = *ppHead; ListNode * pTemp = NULL; ListNode * pNewHead = NULL; if(pHead == NULL) { cout<<"List is NULL, Rev finish... "<<endl; return; } if(pHead->next == NULL) { cout<<"one node only, Rev finish... "<<endl; return; } //find the end node while(pHead != NULL) { //get one node form list and set list head to the next node pTemp = pHead; pHead = pHead->next; cout<<"del "<<pTemp->dat<<" from old list"; //set new node next is newhead and reset new head pTemp->next = pNewHead; pNewHead = pTemp; cout<<" add to new list"<<endl; } *ppHead = pNewHead; } int _tmain(int argc, _TCHAR* argv[]) { #if 1 addList(1); addList(2); addList(3); addList(4); addList(5); printList(); RevList(head); printList(); //RevListParaPP(&head); //printList(); //delListHead(head); delList(); #endif system("pause"); return 0; }