小生努力加载中 . . .

结合LeetCode上203题,学习链表的删除
虽然看不懂,嗯对。


删除链表中的元素

/**
 * 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 delNode = head;
            head = head.next;
            delNode.next = null;
        }

        if(head == null)
        return null;

        ListNode prev = head;
        while(prev.next != null){
            if(prev.next.val == val){
                ListNode delNode = prev.next;
                prev.next = delNode.next;
                delNode.next = null;
            }
            else
            prev = prev.next;
        }

        return head;
    }
}

优化

/**
 * 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)
        head = head.next;

        if(head == null)
        return null;

        ListNode prev = head;
        while(prev.next != null){
            if(prev.next.val == val)
            prev.next = prev.next.next;
            else
            prev = prev.next;
        }

        return head;
    }
}

添加虚拟头结点

看不懂,有点吃力,改日再战

评论