diff --git a/problems/0203.移除链表元素.md b/problems/0203.移除链表元素.md index d6d7e6c2..3b04b1b2 100644 --- a/problems/0203.移除链表元素.md +++ b/problems/0203.移除链表元素.md @@ -497,27 +497,67 @@ func removeElements(_ head: ListNode?, _ val: Int) -> ListNode? { ```php /** - * Definition for singly-linked list. - * type ListNode struct { - * Val int - * Next *ListNode + * Definition for a singly-linked list. + * class ListNode { + * public $val = 0; + * public $next = null; + * function __construct($val = 0, $next = null) { + * $this->val = $val; + * $this->next = $next; + * } * } */ - // 虚拟头+双指针 -func removeElements(head *ListNode, val int) *ListNode { - dummyHead := &ListNode{} - dummyHead.Next = head - pred := dummyHead - cur := head - for cur != nil { - if cur.Val == val { - pred.Next = cur.Next - } else { - pred = cur + +//版本一(在原链表上直接删除): +class Solution { + + /** + * @param ListNode $head + * @param Integer $val + * @return ListNode + */ + function removeElements($head, $val) + { + if ($head == null) { + return null; } - cur = cur.Next + + $now = $head; + while ($now->next != null) { + if ($now->next->val == $val) { + $now->next = $now->next->next; + } else { + $now = $now->next; + } + } + if ($head->val == $val) { + return $head->next; + } + return $head; + } +} + +//版本二(虚拟头结点方式): +class Solution { + + /** + * @param ListNode $head + * @param Integer $val + * @return ListNode + */ + function removeElements($head, $val) + { + $dummyHead = new ListNode(0, $head); + $now = $dummyHead; + while ($now->next != null){ + if ($now->next->val == $val) { + $now->next = $now->next->next; + } else { + $now = $now->next; + } + } + return $dummyHead->next; } - return dummyHead.Next } ```