链表的力扣相关题目
202移除元素
题目:给你一个链表的头节点 head 和一个整数 val ,请你删除链表中所有满足 Node.val == val 的节点,并返回 新的头节点 。
`
/**
- 添加虚节点方式
- 时间复杂度 O(n)
- 空间复杂度 O(1)
- @param head
- @param val
- @return
/
public ListNode removeElements(ListNode head, int val) {
if (head == null) {
return head;
}
// 因为删除可能涉及到头节点,所以设置dummy节点,统一操作
ListNode dummy = new ListNode(-1, head);
ListNode pre = dummy;
ListNode cur = head;
while (cur != null) {
if (cur.val == val) {
pre.next = cur.next;
} else {
pre = cur;
}
cur = cur.next;
}
return dummy.next;
}
/* - 不添加虚拟节点方式
- 时间复杂度 O(n)
- 空间复杂度 O(1)
- @param head
- @param val
- @return
/
public ListNode removeElements(ListNode head, int val) {
while (head != null && head.val == val) {
head = head.next;
}
// 已经为null,提前退出
if (head == null) {
return head;
}
// 已确定当前head.val != val
ListNode pre = head;
ListNode cur = head.next;
while (cur != null) {
if (cur.val == val) {
pre.next = cur.next;
} else {
pre = cur;
}
cur = cur.next;
}
return head;
}
/* - 不添加虚拟节点and pre Node方式
- 时间复杂度 O(n)
- 空间复杂度 O(1)
- @param head
- @param val
- @return
*/
public ListNode removeElements(ListNode head, int val) {
while(head!=null && head.val==val){
head = head.next;
}
ListNode curr = head;
while(curr!=null){
while(curr.next!=null && curr.next.val == val){
curr.next = curr.next.next;
}
curr = curr.next;
}
return head;
}
`
注意事项
- 删除节点一般两种方法,一种是要新建虚拟节点,则会把头节点和后面的节点已相同的处理方法
- 当要处理头节点时,要新建一个节点,把头节点赋给新建的节点,则头节点才不会随意发生改变
浙公网安备 33010602011771号