Merge pull request #2473 from cn-hideyoshi/master

Update 0203.移除链表元素.md- 修改php解法,原解法非php
This commit is contained in:
程序员Carl
2024-04-15 09:42:40 +08:00
committed by GitHub

View File

@ -497,27 +497,67 @@ func removeElements(_ head: ListNode?, _ val: Int) -> ListNode? {
```php ```php
/** /**
* Definition for singly-linked list. * Definition for a singly-linked list.
* type ListNode struct { * class ListNode {
* Val int * public $val = 0;
* Next *ListNode * public $next = null;
* function __construct($val = 0, $next = null) {
* $this->val = $val;
* $this->next = $next;
* }
* } * }
*/ */
// 虚拟头+双指针
func removeElements(head *ListNode, val int) *ListNode { //版本一(在原链表上直接删除):
dummyHead := &ListNode{} class Solution {
dummyHead.Next = head
pred := dummyHead /**
cur := head * @param ListNode $head
for cur != nil { * @param Integer $val
if cur.Val == val { * @return ListNode
pred.Next = cur.Next */
function removeElements($head, $val)
{
if ($head == null) {
return null;
}
$now = $head;
while ($now->next != null) {
if ($now->next->val == $val) {
$now->next = $now->next->next;
} else { } else {
pred = cur $now = $now->next;
} }
cur = cur.Next
} }
return dummyHead.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;
}
} }
``` ```