From 448f9ff77d76515cab7837d89c8425e518b45a51 Mon Sep 17 00:00:00 2001 From: cn-hideyoshi <54949420+cn-hideyoshi@users.noreply.github.com> Date: Sun, 10 Mar 2024 13:32:12 +0800 Subject: [PATCH] =?UTF-8?q?Update=200203.=E7=A7=BB=E9=99=A4=E9=93=BE?= =?UTF-8?q?=E8=A1=A8=E5=85=83=E7=B4=A0.md=20=E6=B7=BB=E5=8A=A0php=E8=A7=A3?= =?UTF-8?q?=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 203.移除链表元素.md 添加php解法 --- problems/0203.移除链表元素.md | 74 ++++++++++++++++++++++------- 1 file changed, 57 insertions(+), 17 deletions(-) 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 } ```