[面试算法题]有序列表删除节点-leetcode学习之旅(4)

问题描述

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 -> 4 after calling your function.

Subscribe to see which companies asked this question
我们需要这样一个函数:从一个单链表中删除指定元素(不能是尾部),这个函数的参数只有这个被删除的节点。

假设这个单链表为 1 -> 2 -> 3 -> 4 。然后你传入的参数节点为第三个,值为3的那个,执行了这个函数之后,这个链表将变为 1 -> 2 -> 4
1 -> 2 -> 3 -> 4
cur next
我得到3这个节点作为参数的时候,把这个节点的指针命名为cur,然后也可以得到4这个节点,把这个节点的指针命名为next,这个时候,我也可以把3这个节点的值改为4,这时链表变为
1 -> 2 -> 4 -> 4
cur next
这时,接着把cur当前的next指针直接指向next的next指针。也就是说之间删掉next的这个节点即可。
这样对于这个链表就变为
1 -> 2 -> 4
结束了!

其实简单来说就是把传入节点的后面一个节点的值赋给自己,然后把自己后面的节点删掉即可。
当然也要注意一下异常检查,代码非常非常简单,这道题也非常非常基础,更是一种思维能力上的考验其实,而我是使用 Java 来写的,所以可以先不用考虑节点的“删除”问题。

java代码实现

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
public class Solution {
public void deleteNode(ListNode node) {
if(node==null||node.next==null) return;
ListNode temp = node.next;
node.val = temp.val;
node.next = temp.next;
}
}
上一篇:【代码笔记】iOS-动画的跳转


下一篇:【Struts2学习笔记(2)】Action默认值和配置Action于result各种转发类型