删除链表中的节点
题目形容:请编写一个函数,使其能够删除某个链表中给定的(非开端)节点。传入函数的惟一参数为 要被删除的节点。
示例阐明请见LeetCode官网。
起源:力扣(LeetCode)
链接:https://leetcode-cn.com/probl...
著作权归领扣网络所有。商业转载请分割官网受权,非商业转载请注明出处。
解法一:脑筋急转弯
第一工夫没反馈过去,为什么没有给head节点???想了会才想明确为什么要强调参数为非开端的节点,解决办法就是将要删的节点的值和next都改成要删节点的next节点的值和next。
public class LeetCode_237 { public static void deleteNode(ListNode node) { node.val = node.next.val; node.next = node.next.next; } public static void main(String[] args) { ListNode head = new ListNode(4); head.next = new ListNode(5); ListNode node_1 = new ListNode(1); head.next.next = node_1; head.next.next.next = new ListNode(9); System.out.println("before deleteNode"); ListNode cur = head; while (cur != null) { System.out.print(cur.val + " "); cur = cur.next; } System.out.println(); deleteNode(node_1); System.out.println("after deleteNode"); while (head != null) { System.out.print(head.val + " "); head = head.next; } }}
【每日寄语】 世上只有一种英雄主义,就是在认清生存假相之后仍然热爱生活。