题目:Remove Linked List Elements
Remove all elements from a linked list of integers that have value val.
Example
Given: 1 --> 2 --> 6 --> 3 --> 4 --> 5 --> 6, val = 6
Return: 1 --> 2 --> 3 --> 4 --> 5
2中间节点的删除比较简单,头节点的删除需要额外考虑。
One:先处理头结点
public class Solution {
public ListNode removeElements(ListNode head, int val) {
if(head==null)return null;
while(head.val==val&&head.next!=null){
head = head.next;
}
if(head.val==val&&head.next==null)return null;
ListNode res = head;
while(head.next!=null){
if(head.next.val==val){head.next=head.next.next;}
else{head = head.next;}
}
return res;
}
}Two :先不管头结点,最后处理头结点
public class Solution {
public ListNode removeElements(ListNode head, int val) {
if(head==null)return null;
ListNode res = head;
while(head.next!=null){
if(head.next.val==val){head.next=head.next.next;}
else{head = head.next;}
}
if(res.val==val)
res = res.next;
return res;
}
}Three:头结点特殊处理,作为新建链表的第二个节点
public class Solution {
public ListNode removeElements(ListNode head, int val) {
if(head==null)return null;
ListNode help = new ListNode(0);
help.next = head;
ListNode cur = help;
while(cur.next!=null){
if(cur.next.val==val){cur.next=cur.next.next;}
else{cur = cur.next;}
}
return help.next;
}
}
Four:递归的方法 简洁
public ListNode removeElements(ListNode head, int val) { if (head == null) return null; head.next = removeElements(head.next, val); return head.val == val ? head.next : head; }
本文介绍了一种从整数链表中移除特定值的所有元素的算法,并提供了四种不同的实现方式,包括直接处理头节点、最后处理头节点、创建辅助节点及递归方法。
739

被折叠的 条评论
为什么被折叠?



