Mon*_*lal 1 java algorithm linked-list data-structures singly-linked-list
你能澄清一下为什么我的代码不能总是删除链表中的所有值等于方法参数中给定的值吗?我该如何解决?它通过了97%的测试用例.我更喜欢修复此问题而不是使用prev/next/dummy指针更改整个方法.
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
/**
* @param head a ListNode
* @param val an integer
* @return a ListNode
*/
public ListNode removeElements(ListNode head, int val) {
while (head!=null && head.val==val){
head = head.next;
}
ListNode tmp=head;
while (tmp!=null) {
if (tmp.next!=null && tmp.next.val== val ) {
tmp.next=tmp.next.next;
}
tmp=tmp.next;
}
if (tmp != null) {
if (tmp.val == val) {
tmp = tmp.next;
}
}
return head;
}
}
Run Code Online (Sandbox Code Playgroud)
它没有通过此测试用例:
Input
5->6->6->null, 6
Output
5->6->null
Expected
5->null
Run Code Online (Sandbox Code Playgroud)
这里有更详细的问题:
Given 1->2->3->3->4->5->3, val = 3, you should return the list as 1->2->4->5
在内部while循环中,更改:
if (tmp.next!=null && tmp.next.val== val ) {
tmp.next=tmp.next.next;
}
Run Code Online (Sandbox Code Playgroud)
至
while (tmp.next!=null && tmp.next.val== val ) {
tmp.next=tmp.next.next;
}
Run Code Online (Sandbox Code Playgroud)
您的版本将跳过要删除的每个连续值对中的第二个值.你做什么:
5-> 6-> 6->空
-tmp:5 - >先删除6,然后将tmp设置为第二个6
-tmp:6,tmp.next:null - >完成(剩下一个6)
| 归档时间: |
|
| 查看次数: |
75 次 |
| 最近记录: |