删除节点
3 -> 2 -> 0 -> 3 -> 4 -> 5
假定删除3这个节点,删除后的链表:2 -> 0 -> 4 -> 5
基本思想
- 存在删除头节点的情况
- 先看是否需要删除头节点以及要删除几个头节点
- 头节点删除完成后,当前节点即为链表的头节点,且作为返回
- 遍历单链表
- 用 cur 表示当前节点,用 pre 表示当前节点的前一个节点,用 num 表示目标值
- 当 cur值 = num时,则将 pre 的next指针指向 cur 的下一个节点(相当于删除了 cur 节点)
- 当 cur值 != num时,则将 pre 右移,cur 右移
代码
public class Node{
public int value;
public Node next;
public Node(int data){
value = data;
}
}
//返回值为删除目标值后的链表的头节点
public static Node removeValue(Node head, int num){
while (head != null){
//判断头节点值是否等于目标值
if (head.value != num){
//直到head值不等于目标值,跳出循环,此时head为返回链表的头节点
break;
}
head = head.next;
}
//定义pre节点作为当前节点的前一个节点
Node pre = null;
//定义cur节点作为遍历的节点
Node cur = head;
//遍历链表
while (cur != null){
//如果当前节点值 = 目标值,则pre节点的next指针指向当前节点的下一个节点
if (cur.value == num){
pre.next = cur.next;
} else {
//如果当前节点值 != 目标值,则pre指向cur节点
pre = cur;
}
//cur节点后移
cur = cur.next;
}
return head
}
复杂度分析
- 时间复杂度:O(n) -> 遍历了单链表
- 空间复杂度:O(1) -> 额外定义了有限个变量,pre cur
版权声明:本文为qq_43337680原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。