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

Example
Given: 1 –> 2 –> 6 –> 3 –> 4 –> 5 –> 6, val = 6
Return: 1 –> 2 –> 3 –> 4 –> 5

Credits:
Special thanks to @mithmatt for adding this problem and creating all test cases.

分析

删除链表中的指定值的节点。

需要注意的是,所需要删除节点的位置,头,中间,尾,不同位置需要不同处理,避免断链~

AC代码

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */

class Solution {
public:
    ListNode* removeElements(ListNode* head, int val) {
        if (head == NULL)
            return head;

        ListNode *pre = head, *p = head;
        while (p)
        {
            //找到要删除的节点元素
            if (p->val == val)
            {
                //判断当前节点为头结点
                if (p == head)
                {
                    head = p->next;
                    ListNode *q = p;
                    //更新头
                    p = head;
                    pre = head;
                    delete q;
                    q = NULL;
                }
                //删除尾节点
                else if (p->next == NULL)
                {
                    pre->next = NULL;               
                    delete p;
                    p = NULL;
                }
                //删除链表中间节点
                else{
                    pre->next = p->next;

                    ListNode *q = p;
                    p = p->next;
                    delete q;
                    q = NULL;
                }//else
            }//if
            else{
                pre = p;
                p = p->next;
            }

        }//while
        return head;
    }
};

GitHub测试程序源码

相关文章:

  • 2021-12-23
  • 2022-01-04
  • 2021-09-04
  • 2022-12-23
  • 2021-07-05
猜你喜欢
  • 2021-07-02
  • 2021-11-20
  • 2021-07-21
  • 2021-10-26
  • 2021-06-11
  • 2022-01-31
  • 2021-09-01
相关资源
相似解决方案