5-5 不仅仅是穿针引线 Delete Node in a Linked List
题目: LeetCode 237. 删除链表中的节点
请编写一个函数,使其可以删除某个链表中给定的(非末尾)节点,你将只被给定要求被删除的节点。
现有一个链表 – head = [4,5,1,9],它可以表示为:
4 -> 5 -> 1 -> 9
示例 1:
输入: head = [4,5,1,9], node = 5
输出: [4,1,9]
解释: 给定你链表中值为 5 的第二个节点,那么在调用了你的函数之后,该链表应变为 4 -> 1 -> 9.
示例 2:
输入: head = [4,5,1,9], node = 1
输出: [4,5,9]
解释: 给定你链表中值为 1 的第三个节点,那么在调用了你的函数之后,该链表应变为 4 -> 5 -> 9.
说明:
链表至少包含两个节点。
链表中所有节点的值都是唯一的。
给定的节点为非末尾节点并且一定是链表中的一个有效节点。
不要从你的函数中返回任何结果。
// 237. Delete Node in a Linked List
// https://leetcode.com/problems/delete-node-in-a-linked-list/description/
// 时间复杂度: O(1)
// 空间复杂度: O(1)
public class Solution {
public void deleteNode(ListNode node) {
// 注意: 这个方法对尾节点不适用。题目中要求了给定的node不是尾节点
// 我们检查node.next, 如果为null则抛出异常, 确保了node不是尾节点
if(node == null || node.next == null)
throw new IllegalArgumentException("node should be valid and can not be the tail node.");
node.val = node.next.val;
node.next = node.next.next;
}
public static void main(String[] args) {
int[] arr = {1, 2, 3, 4};
ListNode head = new ListNode(arr);
System.out.println(head);
ListNode node2 = head.findNode(2);
(new Solution()).deleteNode(node2);
System.out.println(head);
}
}
// Definition for singly-linked list.
// 在Java版本中,我们将LinkedList相关的测试辅助函数写在ListNode里
public class ListNode {
public int val;
public ListNode next = null;
public ListNode(int x) {
val = x;
}
// 根据n个元素的数组arr创建一个链表
// 使用arr为参数,创建另外一个ListNode的构造函数
public ListNode (int[] arr){
if(arr == null || arr.length == 0)
throw new IllegalArgumentException("arr can not be empty");
this.val = arr[0];
ListNode curNode = this;
for(int i = 1 ; i < arr.length ; i ++){
curNode.next = new ListNode(arr[i]);
curNode = curNode.next;
}
}
ListNode findNode(int x){
ListNode curNode = this;
while(curNode != null){
if(curNode.val == x)
return curNode;
curNode = curNode.next;
}
return null;
}
// 返回以当前ListNode为头结点的链表信息字符串
@Override
public String toString(){
StringBuilder s = new StringBuilder("");
ListNode curNode = this;
while(curNode != null){
s.append(Integer.toString(curNode.val));
s.append(" -> ");
curNode = curNode.next;
}
s.append("NULL");
return s.toString();
}
}