做链表提多画图,%99以上都要画图解决
虚拟借点 快慢指针 多指针
1. 输入 1-2-3-4-5-6-5-6;删除掉6的节点
思路:用到虚拟头节点 ,如果是删除的这 head = head.next; 如果不是 newTail.next = head;
newTail = head;
public ListNode removeElements(ListNode head, int val) {
if (head == null) return null;
ListNode newHead = new ListNode(0);
ListNode newTail = newHead;
while (head != null) {
if (head.val != val) {
newTail.next = head;
newTail = head;
}
head = head.next;
}
newTail.next = null;
return newHead.next;
}