Leetcode#203. 移除链表元素(Java解法+虚拟头节点法)

题目描述:

删除链表中等于给定值 val 的所有节点。

示例:

输入: 1->2->6->3->4->5->6, val = 6
输出: 1->2->3->4->5

来源:力扣(LeetCode)

解题思路:

主要解题思路,删除链表中节点即及时更新前驱节点与当前节点即可。但有很多坑值得注意:

需要注意的问题:

1、考虑头结点head的val即为给定值的情况。并且应当用while(不能用if)  针对例如:[7,7,7,7] 7 的值输入

2、尝试并掌握更新前驱结点与当前节点的多种方式

3、学会链表设置虚拟头节点的用法

Java代码:

解法一:

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    public ListNode removeElements(ListNode head, int val) {
        while(head != null && head.val == val){
            head = head.next;
        }
        ListNode node = new ListNode();
        ListNode pre = head;
        if(head != null){
            node = head.next;
        }
        while(node != null){
            if(node.val == val){
                node = node.next;
                pre.next = node;
            }else{
                pre = node;
                node = node.next;
            }
            
        }
        return head;
    }
}

解法二:

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    public ListNode removeElements(ListNode head, int val) {
        ListNode virtualNode = new ListNode();
        virtualNode.next = head;
        ListNode node = virtualNode;
        while(node.next != null){
            if(node.next.val == val){
                node.next = node.next.next;
            }else{
                node = node.next;
            }
        }
        return virtualNode.next;
    }
}

猜你喜欢

转载自blog.csdn.net/paranior/article/details/114490220