Skip to content

Commit

Permalink
删除链表中指定的元素
Browse files Browse the repository at this point in the history
  • Loading branch information
cdtft committed May 12, 2020
1 parent 0abf78f commit 2f4420f
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 0 deletions.
22 changes: 22 additions & 0 deletions src/main/java/com/cdtft/leetcode/Solution.java
Expand Up @@ -8,6 +8,7 @@
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Stack;
import java.util.TreeMap;

Expand Down Expand Up @@ -450,4 +451,25 @@ public int rob(int[] nums) {
return dp1;
}

public ListNode removeElements(ListNode head, int val) {
while (head != null && head.val == val) {
head = head.next;
}
if (head == null) {
return head;
}
ListNode index = head;
while (!Objects.isNull(index.next)) {
if (index.next.val == val) {
index.next = index.next.next;
continue;
}
index = index.next;
if (index == null) {
return head;
}
}
return head;
}

}
6 changes: 6 additions & 0 deletions src/test/java/com/cdtft/leetcode/SolutionTest.java
Expand Up @@ -115,4 +115,10 @@ public void rob() {
int[] nums = new int[]{1, 2, 3, 1};
System.out.println(solution.rob(nums));
}

@Test
public void removeElements() {
ListNode node = new ListNode(1);
solution.removeElements(null, 1);
}
}

0 comments on commit 2f4420f

Please sign in to comment.