237.单链表移除节点 Delete Node in a Linked List

Question

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.

Solution

Approach: Swap with Next Node [Accepted]

The usual way of deleting a node node from a linked list is to modify the next pointer of the node before it, to point to the node after it.

695469-20170110230442306-209979810.png

Since we do not have access to the node before the one we want to delete, we cannot modify the next pointer of that node in any way. Instead, we have to replace the value of the node we want to delete with the value in the node after it, and then delete the node after it.

695469-20170110230442728-1885888317.png

695469-20170110230443306-962978107.png

695469-20170110230443619-139589234.png

Because we know that the node we want to delete is not the tail of the list, we can guarantee that this approach is possible.


 
   
  1. public void DeleteNode(ListNode node) {
  2. node.val = node.next.val;
  3. node.next = node.next.next;
  4. }





转载于:https://www.cnblogs.com/xiejunzhao/p/9d6b2ef73274fbe105d81d0b3bb8df61.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值