LeetCode——203. 移除链表元素(链表)

203. 移除链表元素(链表)

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/remove-linked-list-elements
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

题目**

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

示例:

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

思想**

在头结点前设置一个虚拟结点免去讨论很多特例,比如仅有一个结点且值为val的情况;删除操作用双指针即可

代码**

/**
 * 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) {
        ListNode dummyNode = new ListNode(-1);//哨兵虚节点,避免了许多麻烦
        dummyNode.next = head;
        if(head == null){
            return head;
        }
        ListNode p = head;
        ListNode pre = dummyNode;
        while(p != null){
            if(p.val == val){
                pre.next = p.next;
                p = pre.next;
            }
            else{
                pre = pre.next;
                p = p.next;
            }
        }
        return dummyNode.next;
    }
}

猜你喜欢

转载自blog.csdn.net/qq_34767784/article/details/107279666