mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-07 15:45:40 +08:00
Merge pull request #2473 from cn-hideyoshi/master
Update 0203.移除链表元素.md- 修改php解法,原解法非php
This commit is contained in:
@ -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
|
||||
|
||||
//版本一(在原链表上直接删除):
|
||||
class Solution {
|
||||
|
||||
/**
|
||||
* @param ListNode $head
|
||||
* @param Integer $val
|
||||
* @return ListNode
|
||||
*/
|
||||
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 {
|
||||
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;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
|
Reference in New Issue
Block a user