From 剑指Offer 何海涛 著
#include <iostream> struct ListNode { int m_nValue; ListNode *m_pNext; }; void AddToTail(ListNode **head, int value) { if(head != NULL) { ListNode **curr = head; while(*curr != NULL) { curr = &(*curr)->m_pNext; // 注意: 这里是要移动指针, 而非改变这个指针指向的数据! } *curr = new ListNode; // 注意: 这里是要改变这个指针指向的数据, 而非移动指针! (*curr)->m_nValue = value; (*curr)->m_pNext = NULL; } } void RemoveNode(ListNode **head, int value) { if(head != NULL && *head != NULL) { ListNode **curr = head; while(*curr != NULL && (*curr)->m_nValue != value) { curr = &(*curr)->m_pNext; // 注意: 这里是要移动指针, 而非改变这个指针指向的数据! } if(*curr != NULL) { ListNode *toBeDeleted = *curr; *curr = (*curr)->m_pNext; // 注意: 这里是要改变这个指针指向的数据, 而非移动指针! delete toBeDeleted; } } }
测试集:
void PrintList(const ListNode *head) { const ListNode *curr = head; while(curr != NULL) { std::cout << curr->m_nValue << " -> "; curr = curr->m_pNext; } std::cout << "NULL" << std::endl; } int main(int argc, char *argv[]) { ListNode *head = NULL; AddToTail(&head, 1); AddToTail(&head, 2); AddToTail(&head, 3); AddToTail(&head, 4); AddToTail(&head, 5); PrintList(head); RemoveNode(&head, 1); PrintList(head); RemoveNode(&head, 1); PrintList(head); RemoveNode(&head, 3); PrintList(head); RemoveNode(&head, 5); PrintList(head); RemoveNode(&head, 2); PrintList(head); RemoveNode(&head, 4); PrintList(head); return 0; }