删除一定要有前驱节点
删除一定要有前驱节点
删除一定要有前驱节点
class Solution {
public ListNode removeElements(ListNode head, int val) {
// 这题没有头节点,莫名其妙,创建一个虚拟头节点,方便处理头元素
ListNode dummyHead = new ListNode();
dummyHead.next = head;
ListNode cur = dummyHead; // 直接把虚拟头节点进行赋值
while(cur.next != null){ // 删除操作一定要有前驱节点
if(cur.next.val == val){
cur.next = cur.next.next;
}else{
cur = cur.next;
}
}
return dummyHead.next;
}
}
class Solution {
public ListNode reverseList(ListNode head) {
ListNode dummyNew = new ListNode();
if(head == null) return dummyNew.next;
ListNode cur = head ;
while(cur != null){// 本题对于原始链表的遍历没有使用前驱节点,删除的时候才必须有先驱 谨记
ListNode temp = cur;
cur = cur.next;
temp.next = dummyNew.next;// 新链表 头插法
dummyNew.next = temp;
// cur = cur.next;
}
return dummyNew.next;
}
}