leetcode| Delete Node in a Linked List

Write a function to delete a node (except the tail) in a singly linked list, given only access to that node.

Supposed the linked list is 1 -> 2 -> 3 -> 4 and you are given the third node with value 3, the linked list should become 1 -> 2 -> 4after calling your function.

题目:不翻译了,大概意思就是给你一个给你一个链表,删除之

思路:该题诡异之处的就是,它就给你一个要删除的链表,链表表的其他的信息一概不知,根据题目对链表这个类ListNode的定义,可知两个信息当前链表的值以及一啊一个节点

public class ListNode {

  int val;  

  ListNode next;

  ListNode(int x) { val = x; }
 }

所以,我们只能从这两个信息下手,既然是删除,就是链表节点的值不能存在,在信息少的情况下,不能存在意思就是让别的值替代,两个信息中只能用next替代,那么next用谁替代呢,next.next啊,以此下去,代码如下:

public void deleteNode(ListNode node) {

   node.val = node.next.val;

   node.next = node.next.next;

}

如此一来,当前的node的信息就是完全被node.next代替,更新完后达到删除效果!

原文地址:https://www.cnblogs.com/wujunjie/p/5687080.html