用递归思想删除链表中的元素

package DataDtructure;

/**
 * ClassName: RemoveListNode
 * Company:华中科技大学电气学院
 * date: 2019/8/26 15:22
 * author: YEXIN
 * version: 1.0
 * since: JDK 1.8
 * Description:通过递归删除链表中的节点
 */
public class RemoveListNode {

    public ListNode removeElements(ListNode head,E val){//穿入一个链表头head
        if (head == null)
            return null;

        head.next = removeElements(head.next,val);
//        if (head.val == val)
//            return head.next;
//        else
//            return head;

        return head.val == val?head.next:head;

    }


    public static void main(String[] args) {
        Integer[] nums = {2,2,34,4,467,3,45,2,3,5,3,2};
        ListNode head = new ListNode((nums));//用数组生成的链表用一个head引用来表示,head指向头节点
        System.out.println(head.toString());

        ListNode res = (new RemoveListNode<>()).removeElements(head, 2);//链表的引用指向头结点!!!!
        System.out.println(res.toString());
    }
}

你可能感兴趣的:(Java)