mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-07 15:45:40 +08:00
Merge pull request #2579 from MengyiG/mengyi203
Update problem 203 Java solution
This commit is contained in:
@ -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 curr = head;
|
||||
while(curr!=null){
|
||||
while(curr.next!=null && curr.next.val == val){
|
||||
curr.next = curr.next.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;
|
||||
}
|
||||
curr = curr.next;
|
||||
}
|
||||
return head;
|
||||
return dummy.next;
|
||||
}
|
||||
|
||||
```
|
||||
|
||||
### Python:
|
||||
|
Reference in New Issue
Block a user