[leetcode]203.Remove Linked List Elements

题目

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

Example:

Input: 1->2->6->3->4->5->6, val = 6
Output: 1->2->3->4->5

解法

思路

思路不难。。。就是很繁琐。。。其实可以加一个头结点,这样会好写很多。。最后只要返回头结点的next即可。

代码

/**
 * 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 fakehead = new ListNode(0);
        fakehead.next = head;
        ListNode p = fakehead;
        while(head != null) {
            if(head.val == val) {
                p.next = head.next;
                head = head.next;
            }else {
                p = head;
                head = head.next;
            }
        }
        return fakehead.next;
    }
}

还有一种不带头结点的写法。要考虑的情况有点多。。。

/**
 * 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 head;
        ListNode p = head;
        while(p.next != null) {
            if(p.next.val == val) p.next = p.next.next;
            else p = p.next;
        }
        return head.val == val ? head.next : head;
    }
}
posted @ 2018-10-12 10:16  shinjia  阅读(90)  评论(0编辑  收藏  举报