203、移除链表元素
解法一
class Solution {
public ListNode removeElements(ListNode head, int val) {
while(head != null && head.val == val) {
ListNode node = head;
head = head.next;
node.next = null;
}
if(head == null) {
return null;
} else {
ListNode prev = head;
while(prev.next != null) {
if(prev.next.val == val) {
ListNode node = prev.next;
prev.next = node.next;
node.next = null;
} else {
prev = prev.next;
}
}
return head;
}
}
}
运行截图: 解法二(虚拟头结点)
class Solution {
public ListNode removeElements(ListNode head, int val) {
ListNode dummyHead = new ListNode(-1);
dummyHead.next = head;
ListNode prev = dummyHead;
while(prev.next != null) {
if (prev.next.val == val) {
ListNode node = prev.next;
prev.next = node.next;
node.next = null;
} else {
prev = prev.next;
}
}
return dummyHead.next;
}
}
运行截图: 解法三(递归)
class Solution {
public ListNode removeElements(ListNode head, int val) {
if(head == null) {
return null;
}
head.next = removeElements(head.next,val);
if(head.val == val) {
return head.next;
}
return head;
}
}
简化:
class Solution {
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;
}
}
运行截图:
|