删除链表中等于给定值 val 的所有节点。
示例:
输入: 1->2->6->3->4->5->6, val = 6
输出: 1->2->3->4->5
我的代码:
效率很低,实现的很简单,首先就是获取第一个不是val的字符,之后创建一个新节点,然后一直判断,比较笨拙
class Solution {
public ListNode removeElements(ListNode head, int val) {
ListNode list = head;
ListNode head1 = head;
while (list!=null) {
if(list.val == val ){
list = list.next;
}else {
break;
}
}
if(list == null){
return null;
}
ListNode re = new ListNode(list.val);
list = list.next;
ListNode res = re;
while (list !=null) {
if(list.val == val){
list = list.next;
}else{
ListNode list2 = new ListNode(list.val);
re.next = list2;
re = re.next;
list = list.next;
}
}
return res;
}
}
跟这个思路差不多
class Solution {
public ListNode removeElements(ListNode head, int val) {
ListNode dummy = new ListNode(-1),pre = dummy;
dummy.next = head;
while(pre != null) {
ListNode cur = pre.next;
while (cur != null && cur.val == val) cur = cur.next;
pre.next = cur;
pre = pre.next;
}
return dummy.next;
}
}
考虑使用递归来实现,判断当前的数字是否等于val如果等于就返回.next,否则就是head
class Solution {
public ListNode removeElements(ListNode head, int val) {
if (head == null)
return head;
head.next = removeElements(head.next, val);
return head.val == val ? head.next : head;
}
}