给定单向链表的头指针和一个要删除的节点的值,定义一个函数删除该节点。返回删除后的链表的头节点。
思路:单指针,找到需要删除的节点的前一个节点即可。
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode deleteNode(ListNode head, int val) {
if (head == null){
return head;
}
if (head.val == val){ //头节点是需要删除的节点
return head.next;
}
ListNode cur = head;
while (cur.next != null && cur.next.val != val){
cur = cur.next;
}
if (cur.next != null){
cur.next = cur.next.next;
}
return head;
}
}
双指针:
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode deleteNode(ListNode head, int val) {
if (head == null){
return head;
}
if (head.val == val){
return head.next;
}
ListNode pre = head;
ListNode cur = head.next;
while (cur != null && cur.val != val){
pre = cur;
cur = cur.next;
}
if (cur != null) pre.next = cur.next;
return head;
}
}
时间复杂度:O(N) 空间复杂度:O(1)