数据结构---移除链表中值为val的元素

删除链表中等于给定值 val 的所有节点。
示例 :
输入 : 1->2->6->3->4->5->6, val = 6
输出 : 1->2->3->4->5

struct ListNode {
    int val;
    ListNode *next;
    ListNode(int x) : val(x), next(NULL) {}
 };
 

思路:定义两个指针(比如pPre,pCur),让pPre指向头结点,让pCur指向头的下一个结点,然后一起向前走,找值为val的节点。找到后更新pPre,删除pCur指向的结点就好了。当然,头结点值可能也是val,我们最后再判断,然后看是否要删除就好

class Solution {
public:
 ListNode* removeElements(ListNode* head, int val) {
  if (!head)return head;
  struct ListNode* pPre = head;
  struct ListNode* pCur = pPre->next;
  while (pCur)
  {
   if (pCur->val == val)
   {
    pPre->next = pCur->next;
    pCur = pPre->next;
   }
   else
   {
    pPre = pCur;
    pCur = pCur->next;
   }
  }
  if (head->val == val)
   head = head->next;
  return head;
 }
};
发布了78 篇原创文章 · 获赞 2 · 访问量 3319

猜你喜欢

转载自blog.csdn.net/weixin_43219708/article/details/104644278