Question
203. Remove Linked List Elements
Solution
题目大意:从链表中删除给定的数
思路:遍历链表,如果该节点的值等于给的数就删除该节点,注意首节点
Java实现:
public ListNode removeElements(ListNode head, int val) {
ListNode cur = head;
while (cur != null) {
if (cur.next != null && cur.next.val == val) {
ListNode tmp = cur.next.next;
cur.next = tmp;
} else {
cur = cur.next;
}
}
return (head != null && head.val == val) ? head.next : head;
}