自己写的简短代码搜集
原创
©著作权归作者所有:来自51CTO博客作者飞翔的葱油饼的原创作品,请联系作者获取转载授权,否则将追究法律责任
LeetCode 203 移除链表元素
// 递归解法
class Solution {
public ListNode removeElements(ListNode head, int val) {
if(head == null) return null;
ListNode tail = removeElements(head.next, val);
if(head.val == val) return tail;
head.next = tail;
return head;
}
}
// 迭代解法
class Solution {
public ListNode removeElements(ListNode head, int val) {
ListNode hh = new ListNode(0, head), pre = hh;
while(pre.next != null) {
if(pre.next.val == val) pre.next = pre.next.next;
else pre = pre.next;
}
return hh.next;
}
}