LeetCode(2) -- Remove Linked List Elements

来源:互联网 发布:gta5低特效优化补丁 编辑:程序博客网 时间:2024/06/06 01:41

链表 - Remove Linked List Elements


Remove Linked List Elements

描述:
Remove all elements from a linked list of integers that have value val.

从一个链表中删除所有指定元素值的整数

ExampleGiven: 1 --> 2 --> 6 --> 3 --> 4 --> 5 --> 6, val = 6Return: 1 --> 2 --> 3 --> 4 --> 5
思路:    需要保证头指针的准确,有可能前面连续三个 四个 都是指定要删除的数值,这个个数是不确定的

算法:

/** * 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;        }        //为了确保head的准确        while (head.val == val){            if(head.next != null){                head = head.next;            }else {                return null;            }        }        ListNode before = head;        if(head.next != null){            ListNode target = head.next;            while (target != null){                if(target.val == val){                    before.next = target.next;                    target = before.next;                }else {                    before = target;                    target = before.next;                }            }        }        return head;    }}
原创粉丝点击