跳至主要內容

LeetCode 203.移除链表元素

张威小于 1 分钟数据结构与算法链表虚拟头结点

LeetCode 203.移除链表元素open in new window

题目描述:给定链表头节点head和整数val,删除所有值为val的节点 ,返回新的头节点

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    ListNode* removeElements(ListNode* head, int val) {
       ListNode* dummyHead = new ListNode(0, head);
       ListNode* cur = dummyHead;
       while(cur->next) {
           if(cur->next->val == val) {	//cur->next->val不是cur->next.val
               ListNode* temp = cur->next;
               cur->next = cur->next->next;
               delete temp;
               temp = nullptr;
           }
           else {
               cur = cur->next;
           }
       }
       head = dummyHead->next;
       delete dummyHead;
       dummyHead = nullptr;
       return head;
    }
};
  1. 删除结点后记得释放结点,然后将指针置空