[LeetCode]203. Remove Linked List Elements 解题报告(C++)

[LeetCode]203. Remove Linked List Elements 解题报告(C++)

题目描述

Remove all elements from a linked list of integers that have value val.

Example:

Input:  1->2->6->3->4->5->6, val = 6
Output: 1->2->3->4->5

题目大意

  • 移除单链表中给定 val 的节点.

解题思路

方法1:

  • 移除某个节点.需要前驱
  • 若是在头节点.没有前驱.需要特殊处理.

代码实现:


class Solution {
public:
    ListNode* removeElements(ListNode* head, int val) {
        ListNode *pre, *cur;
        pre = head;
        bool first = false;
        if (pre&&pre->val == val) {
            first = true;
        }
        if (pre) {
            cur = pre->next;
        }
        while (cur) {
            if (cur->val == val) {
                pre->next = cur->next;
            }
            else {
                pre = cur;
            }
            cur = pre->next;
        }
        return first ? head->next : head;
    }
};

方法2:

  • 创建一个节点.把给定链表的节点接到后面.主要就有前驱了.
  • 然后去遍历判断即可.

代码实现:

class Solution {
public:
    ListNode* removeElements(ListNode* head, int val) {
        ListNode *dummy = (ListNode*)malloc(sizeof(ListNode));
        dummy->next = head;
        ListNode *pre = dummy;
        while (pre->next) {
            if (pre->next->val == val) {
                ListNode *tmp = pre->next;
                pre->next = tmp->next;
                tmp->next = NULL;
                delete tmp;
            }
            else {
                pre = pre->next;
            }
        }
        return dummy->next;
    }
};

方法3:

  • 递归
  • 通过递归调用到链表末尾. 然后再返回.需要要删除的元素.将链表的next指针指向下一个元素.

代码实现:

class Solution{
public:
    ListNode* removeElements(ListNode* head, int val) {
        if (!head) return NULL;
        head->next = removeElements(head->next, val);
        return head->val == val ? head->next:head;
    }
};

你可能感兴趣的:([解题报告])