移除链表元素(203)

  1. 移除链表元素
    删除链表中等于给定值 val 的所有节点。

示例:
输入: 1->2->6->3->4->5->6, val = 6
输出: 1->2->3->4->5
力扣原题链接
创建伪头结点:

/**
 * 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) {
  if (head == nullptr)
              return nullptr;
          ListNode* sentr = new ListNode();//申请一个伪头结点
          sentr->next = head;
          ListNode* prear = sentr;
          ListNode* pfro = head;
          while (pfro) {
              if (pfro->val == val) {
                  prear->next = pfro->next;
                  pfro=pfro->next;
              }
              else{
              prear = prear->next;
              pfro = pfro->next;
              }
          }
          return sentr->next;
    }
};
posted @ 2021-01-23 18:41  nepu_bin  阅读(41)  评论(0)    收藏  举报