鏈表結點與函數的定義如下:
struct ListNode { int m_nValue; ListNode* m_pNext; }; void DeleteNode(ListNode** pListHead,ListNode* pToBeDeleted);
思路:我們可以很方便的得到要刪除的結點的下一結點,如果我們把下一個結點的內容復制到需要刪除的結點上覆蓋原有的內容,再把下一個結點刪除。就相當於把當前需要刪除的結點給刪除了。
實現代碼如下:
1 #include<iostream> 2 #include<stdlib.h> 3 using namespace std; 4 5 //鏈表結構 6 struct ListNode 7 { 8 int m_nValue; 9 ListNode* m_pNext; 10 }; 11 12 //創建一個鏈表結點 13 ListNode* CreateListNode(int value) 14 { 15 ListNode *pNode = new ListNode(); 16 pNode->m_nValue=value; 17 pNode->m_pNext=NULL; 18 return pNode; 19 20 } 21 22 //遍歷鏈表中所有結點 23 void PrintList(ListNode* pHead) 24 { 25 ListNode *pNode = pHead; 26 while(pNode!=NULL) 27 { 28 cout<<pNode->m_nValue<<" "; 29 pNode=pNode->m_pNext; 30 } 31 cout<<endl; 32 } 33 //連接兩個結點 34 void ConnectListNode(ListNode *pCurrent,ListNode* pNext) 35 { 36 if(pCurrent==NULL) 37 { 38 cout<<"前一個結點不能為空"<<endl; 39 exit(1); 40 } 41 else 42 { 43 pCurrent->m_pNext=pNext; 44 } 45 } 46 47 //刪除鏈表 48 void DestroyList(ListNode* pHead) 49 { 50 ListNode* pNode = pHead; 51 while(pNode != NULL) 52 { 53 pHead = pHead->m_pNext; 54 delete pNode; 55 pNode = pHead; 56 } 57 } 58 59 60 61 62 //考慮四種不同的情況 63 void DeleteNode(ListNode** pListHead, ListNode* pTobeDeleted) 64 { 65 if(!pListHead || !pTobeDeleted) 66 return; 67 68 //要刪除的結點不是尾結點 69 if(pTobeDeleted->m_pNext != NULL) 70 { 71 ListNode* pNext = pTobeDeleted->m_pNext; 72 pTobeDeleted->m_nValue = pNext->m_nValue; 73 pTobeDeleted->m_pNext = pNext->m_pNext; 74 75 delete pNext; 76 pNext = NULL; 77 } 78 //鏈表只有一個結點,刪除頭結點(也是尾結點) 79 else if(*pListHead == pTobeDeleted) 80 { 81 delete pTobeDeleted; 82 pTobeDeleted = NULL; 83 *pListHead = NULL; 84 } 85 //鏈表中有多個結點,刪除尾結點 ,只能遍歷鏈表 86 else 87 { 88 ListNode* pNode = *pListHead; 89 while(pNode->m_pNext != pTobeDeleted) 90 { 91 pNode = pNode->m_pNext; 92 } 93 94 pNode->m_pNext = NULL; 95 delete pTobeDeleted; 96 pTobeDeleted = NULL; 97 } 98 } 99 100 int main() 101 { 102 //創建結點 103 ListNode* pNode1 = CreateListNode(1); 104 ListNode* pNode2 = CreateListNode(2); 105 ListNode* pNode3 = CreateListNode(3); 106 ListNode* pNode4 = CreateListNode(4); 107 ListNode* pNode5 = CreateListNode(5); 108 ListNode* pNode6 = CreateListNode(6); 109 ListNode* pNode7 = CreateListNode(7); 110 //連接結點 111 ConnectListNode(pNode1,pNode2); 112 ConnectListNode(pNode2,pNode3); 113 ConnectListNode(pNode3,pNode4); 114 ConnectListNode(pNode4,pNode5); 115 ConnectListNode(pNode5,pNode6); 116 ConnectListNode(pNode6,pNode7); 117 118 PrintList(pNode1); 119 //刪除結點 120 DeleteNode(&pNode1,pNode4); 121 //打印鏈表 122 PrintList(pNode1); 123 //刪除鏈表 124 DestroyList(pNode1); 125 126 return 0 ; 127 }
運行結果如下: