随笔-移除链表元素

版权声明:中华人民共和国持有版权 https://blog.csdn.net/Fly_Fly_Zhang/article/details/85329185

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

示例:

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

思路:主要有几个临界点,因为leetcode上的链表题,所有的头结点都算值节点,所以暂时将它当头结点使用,去除其他节点的val值之后,在判断它是不是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) {
        if(head==null){
            return null;
        }
        ListNode pre=head;
        while(pre.next!=null){
            if(pre.next.val==val){
                pre.next=pre.next.next; //删除val结点
            }else{
                 pre=pre.next;
            }
        }
        head= head.val==val? head.next :head;
        return head;
    }
}

猜你喜欢

转载自blog.csdn.net/Fly_Fly_Zhang/article/details/85329185