203.移除链表元素
两种写法,有虚拟头节点的能让删除操作统一。
不用虚拟头节点的,判断头节点时候用的时真的head指针而不是cur指针。
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode removeElements(ListNode head, int val) {
/*用假头节点
ListNode dummyHead = new ListNode();
dummyHead.next = head;
ListNode cur = new ListNode();
cur = dummyHead;
while(cur != null && cur.next != null){
if(cur.next.val == val){
cur.next = cur.next.next;
}else{
cur = cur.next;
}
}
return dummyHead.next;
*/
//不用假头节点
ListNode cur = new ListNode();
//用while不是if,因为第一个头节点被删除后面会顶上
while(head != null && head.val == val ){
head = head.next;
}
cur = head;
while(cur!= null && cur.next != null){
if(val == cur.next.val){
cur.next = cur.next.next;
}else{
cur = cur.next;
}
}
return head;
}
}
707.设计链表
使用虚拟头节点,注意给ListNode添加空参构造,不然力扣不会自动添加。使用虚拟头节点,添加元素可以让头插法和尾插法直接调用添加元素的操作。
206.反转链表
双指针解法,注意要用temp临时存储节点,防止找不到。