LeetCode--Remove Linked List Element

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

Solution1: 不使用头结点。  

注意事项:while停止的条件要特备注意;各种输入情况都要考虑到;如果首节点就是要删除的节点肿么办,等等问题。

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
public class Solution {
    public ListNode removeElements(ListNode head, int val) {
         if(head == null)
              return null;
          if(head.next==null && head.val==val)
              return null;
          if(head.next==null && head.val!=val)
              return head;
          ListNode p = head;
          
          while(head.next!=null && head.val==val){
              p = head;
              head = head.next;
              p.next = null;
          }
          
          p = head;
          ListNode q = p.next;
          while(p.next!=null){
              q = p.next;
              if(q.val == val){
                  p.next = q.next;
                  q.next = null;
              }
              else{
                  p = q;
                  q = p.next;
              }
          }
          if(head.val==val)//做最后的检查,看是否首节点是要删除的元素
              return null;
          return head;
         
    }
}

Solution2: 使用附加头结点。

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
public class Solution {
    public ListNode removeElements(ListNode head, int val) {
       if(head == null || head.val == val && head.next == null) return null;
        ListNode h = new ListNode(-1);
        h.next = head;
        ListNode p = h;
        ListNode q;
        while(p.next != null) {
            if(p.next.val == val) {
                q = p.next;
                p.next = q.next;
                q.next = null;
            }
            else 
                p = p.next;
        }
        return h.next;
    }
}
原文地址:https://www.cnblogs.com/little-YTMM/p/4511473.html