update project 203 java version solution

This commit is contained in:
mengyi
2024-06-09 21:30:32 -04:00
parent bafc930a8a
commit ddc8e2de60

View File

@ -224,9 +224,10 @@ struct ListNode* removeElements(struct ListNode* head, int val){
### Java
用原来的链表操作:
```java
/**
* 添加虚节点方式
* 方法1
* 时间复杂度 O(n)
* 空间复杂度 O(1)
* @param head
@ -234,25 +235,22 @@ struct ListNode* removeElements(struct ListNode* head, int val){
* @return
*/
public ListNode removeElements(ListNode head, int val) {
if (head == null) {
return head;
while(head!=null && head.val==val) {
head = head.next;
}
// 因为删除可能涉及到头节点所以设置dummy节点统一操作
ListNode dummy = new ListNode(-1, head);
ListNode pre = dummy;
ListNode cur = head;
while (cur != null) {
if (cur.val == val) {
pre.next = cur.next;
ListNode curr = head;
while(curr!=null && curr.next !=null) {
if(curr.next.val == val){
curr.next = curr.next.next;
} else {
pre = cur;
curr = curr.next;
}
cur = cur.next;
}
return dummy.next;
return head;
}
/**
* 不添加虚拟节点方式
* 方法1
* 时间复杂度 O(n)
* 空间复杂度 O(1)
* @param head
@ -280,8 +278,13 @@ public ListNode removeElements(ListNode head, int val) {
}
return head;
}
```
设置一个虚拟头结点:
```java
/**
* 不添加虚拟节点and pre Node方式
* 时间复杂度 O(n)
* 空间复杂度 O(1)
* @param head
@ -289,18 +292,21 @@ public ListNode removeElements(ListNode head, int val) {
* @return
*/
public ListNode removeElements(ListNode head, int val) {
while(head!=null && head.val==val){
head = head.next;
// 设置一个虚拟的头结点
ListNode dummy = new ListNode();
dummy.next = head;
ListNode cur = dummy;
while (cur.next != null) {
if (cur.next.val == val) {
cur.next = cur.next.next;
} else {
cur = cur.next;
}
ListNode curr = head;
while(curr!=null){
while(curr.next!=null && curr.next.val == val){
curr.next = curr.next.next;
}
curr = curr.next;
}
return head;
return dummy.next;
}
```
### Python