• 203.移除链表元素 :::info 可以设置一个虚拟头结点,这样原链表的所有节点就都可以按照统一的方式进行移除了。 ::: 代码:(详细注释)
      1. class Solution {
      2. public:
      3. ListNode* removeElements(ListNode* head, int val) {
      4. ListNode* dummyHead = new ListNode(0); // 设置一个虚拟头结点
      5. dummyHead->next = head; // 将虚拟头结点指向head,这样方面后面做删除操作
      6. ListNode* cur = dummyHead;
      7. while (cur->next != NULL) {
      8. if(cur->next->val == val) {
      9. ListNode* tmp = cur->next;
      10. cur->next = cur->next->next;
      11. delete tmp;
      12. } else {
      13. cur = cur->next;
      14. }
      15. }
      16. head = dummyHead->next;
      17. delete dummyHead;
      18. return head;
      19. }
      20. };
      分析:
      使用假头的方法