删除单链表元素-链表相关
作者:互联网
做链表提多画图,%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;
}
标签:head,单链,ListNode,删除,newTail,next,链表,null,newHead 来源: https://www.cnblogs.com/syh918/p/14934848.html