203 移除链表元素

题目描述:删除链表中等于给定值 val 的所有节点。

示例:

输入: 1->2->6->3->4->5->6, val = 6
输出: 1->2->3->4->5
解题思路:
因为这是一道容易题,刚拿到题目就按照我设想的思路往下写,我的思路就是遍历,判断值是否相等,相等则让其下一个指针重新指向下下一个元素,下面注释的部分是我写出来的代码,运行发现这个方法运行超时了,具体原因不知道为什么
然后看了题解的其他方法,发现val的值要考虑很多,比如说它是否出现在头尾,或者出现在中间,而出现在头尾的情况是我没有考虑到的,只是设想到了val出现在中间的一般情况。
后来看到别人的方法是设置哨兵,在头结点的前一个节点设置哨兵,这样的话val无论出现在哪里解决的办法都是一样的了。
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */


struct ListNode* removeElements(struct ListNode* head, int val){
   //if (head==NULL)//考虑边缘情况
   //{
      //return NULL;
   //}
   //最容易想到的方法是遍历链表,然后找到重复的元素之后保存那个重复元素,然后删除
   //while(head!=NULL)
   //{
       //struct  ListNode *p=head;
      // struct ListNode *q;
       //if(p->val==val)
       //{
           //q=p;
           //p->next=p->next->next;
          // free(q);
       //}
      //else
      //{
       // p=p->next;
      // }
   //}
   //return head;
    
    struct ListNode *sentry=(struct ListNode*)malloc(sizeof(struct ListNode));
    sentry->next=head;
    struct ListNode *curr=head,*pre=sentry;
    while(curr!=NULL)
    {
        if(curr->val==val)
        {
            pre->next=curr->next;
        }
        else{
            pre=curr;
        }
        curr=curr->next;
    }
    return sentry->next;    
}

  总结:

代码中下面写的这种方法是要申请一个哨兵节点,然后指向头节点。就是指针指向一个节点。

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */


struct ListNoderemoveElements(struct ListNodeheadint val){
   //if (head==NULL)//考虑边缘情况
   //{
      //return NULL;
   //}
   //最容易想到的方法是遍历链表,然后找到重复的元素之后保存那个重复元素,然后删除
   //while(head!=NULL)
   //{
       //struct  ListNode *p=head;
      // struct ListNode *q;
       //if(p->val==val)
       //{
           //q=p;
           //p->next=p->next->next;
          // free(q);
       //}
      //else
      //{
       // p=p->next;
      // }
   //}
   //return head;
    
    struct ListNode *sentry=(struct ListNode*)malloc(sizeof(struct ListNode));
    sentry->next=head;
    struct ListNode *curr=head,*pre=sentry;
    while(curr!=NULL)
    {
        if(curr->val==val)
        {
            pre->next=curr->next;
        }
        else{
            pre=curr;
        }
        curr=curr->next;
    }
    return sentry->next;    
}
原文地址:https://www.cnblogs.com/redzzy/p/13300136.html