203Remove Linked List Elements

来源:互联网 发布:linux 查看进程cpu 编辑:程序博客网 时间:2024/05/22 01:52

题目链接:https://leetcode.com/problems/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

解题思路:
这题的考点是链表的操作
思路很普通,一次遍历将等于 val 的结点删除即可。
需要注意的是一些特别的情况。
例如:
1. 要删除的结点在链表头。使用 while 循环,使 head 定位到第一个不用删除的结点上。
2. 要删除的结点在链表尾。同过 while(q != null) 来控制
3. 整个链表的结点都是需要删除的结点。

小技巧:在头结点之前再创建一个结点,这样就能将删除第一个结点的情况归为一般情况。

代码实现:

/** * Definition for singly-linked list. * public class ListNode { *     int val; *     ListNode next; *     ListNode(int x) { val = x; } * } */public class Solution {    public ListNode removeElements(ListNode head, int val) {        if(head == null)            return head;        while(head != null && head.val == val)            head = head.next;        if(head == null || head.next == null)            return head;        ListNode p = head;        ListNode q = head.next;        while(q != null) {            if(q.val == val) {                ListNode tmp = q;                q = q.next;                p.next = q;            } else {                p = p.next;                q = q.next;            }        }        return head;    }}
63 / 63 test cases passed.Status: AcceptedRuntime: 2 ms

方法二:

/** * Definition for singly-linked list. * public class ListNode { *     int val; *     ListNode next; *     ListNode(int x) { val = x; } * } */public class Solution {    public ListNode removeElements(ListNode head, int val) {        ListNode helper = new ListNode(0);        helper.next = head;        ListNode p = helper;        while(p.next != null){            if(p.next.val == val){                ListNode next = p.next;                p.next = next.next;             }else{                p = p.next;            }        }        return helper.next;    }}
63 / 63 test cases passed.Status: AcceptedRuntime: 2 ms
0 0