LeetCode 203-- remove list (JAVA)

Delete the list is equal to a given value  val  all nodes.

Example:

Input: 1-> 2-> 6-> 3-> 4-> 5->. 6, Val =. 6 
Output: 1-> 2-> 3-> 4-> 5

Directly on the code:

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution 
{
    public ListNode removeElements(ListNode head, int val) 
    {
        while(head!=null&&head.val==val)//初始化
        {
            ListNode pre=head;
            head=pre.next;
            pre.next=null;
        }
        if(head==null ) // head node is empty 
        {
             return  null ; 
        } 
        ListNode pre = head;
         the while ! (pre.next = null ) 
        { 
            ListNode CUR = pre.next;
             IF (Cur.Val == Val) // remove nodes 
            { 
                pre.next = cur.next; 
                cur.next = null ; 
            } 
            the else  // move the pointer 
            { 
                pre = pre.next;
            }
        }
       return head;
    }
} 

Traverse the list to find each node in front of each node to be deleted.

Special circumstances: The first node is the node to be deleted, to conduct a separate operation.

Precautions: When entering 1-> 1, completely remove the first node, the remaining nodes of the head of the list is to be deleted node.

 

Guess you like

Origin www.cnblogs.com/jiameng991010/p/11260241.html