203 Remove Linked List Elements

注意使用假节点的技巧

Python

# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution(object):
    def removeElements(self, head, val):
        """
        :type head: ListNode
        :type val: int
        :rtype: ListNode
        """
        p = head
        new_head = None
        cur = None
        while p:
            if p.val!=val:
                if new_head is None:
                    new_head = ListNode(p.val)
                    cur = new_head
                else:
                    cur.next = ListNode(p.val)
                    cur = cur.next
            p = p.next
        return new_head

Java

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

results matching ""

    No results matching ""