leecode 203. 移除链表元素

/**
 * Created by zhanghaipeng on 2019/8/6.
 * 删除链表中等于给定值 val 的所有节点。
 * leecode 203. 移除链表元素
 * 示例:
 * 输入: 1->2->6->3->4->5->6, val = 6
 * 输出: 1->2->3->4->5
 */
public class removeElementsLink {

    public ListNode removeElements(ListNode head, int val) {
        ListNode res = new ListNode (-1);
        res.next = head;

        ListNode pre = res;
        ListNode cur =  null;
        if(head == null){
            return null;
        }else{
            cur = head;
        }

        while(cur != null){
            if(cur.val == val){
                pre.next = cur.next;
                cur = cur.next;
            }else {
                pre = cur;
                cur = cur.next;
            }
        }

        return res.next;
    }

    public static void main(String[] args){
        ListNode head = new ListNode (0);
        ListNode n1 = new ListNode (1);
        ListNode n2 = new ListNode (2);
        ListNode n3 = new ListNode (3);
        ListNode n4 = new ListNode (4);
        ListNode n5 = new ListNode (5);
        ListNode n6 = new ListNode (6);
        head.next = n1;
        n1.next = n2;
        n2.next = n3;
        n3.next = n4;
        n4.next = n5;
        n5.next = n6;
        ListNode node = new removeElementsLink ().removeElements (head,2);
    }
}

你可能感兴趣的:(链表,算法,算法,链表,leecode)