Write a function to delete a node (except the tail) in a singly linked list, given only access to that node.
Given linked list – head = [4,5,1,9], which looks like following:
Example 1:
Input: head = [4,5,1,9], node = 5
Output: [4,1,9]
Explanation: You are given the second node with value 5, the linked list should become 4 -> 1 -> 9 after calling your function.
Example 2:
Input: head = [4,5,1,9], node = 1
Output: [4,5,9]
Explanation: You are given the third node with value 1, the linked list should become 4 -> 5 -> 9 after calling your function.
Note:
请编写一个函数,使其可以删除某个链表中给定的(非末尾)节点,你将只被给定要求被删除的节点。
现有一个链表 – head = [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.
说明:
/**
* Definition for singly-linked list.
* public class ListNode {
* public int val;
* public ListNode next;
* public ListNode(int x) { val = x; }
* }
*/
public class Solution
{
public void DeleteNode(ListNode node)
{
//给我们的这个node就是链表的一部分,直接在上面操作就可以了。
ListNode temp = node.next;
while (temp != null)
{
node.val = temp.val;
temp = temp.next;
if (temp != null)
{
node = node.next;
}
}
node.next = null;
}
}
1. “数组”类算法
2. “链表”类算法
3. “栈”类算法
4. “队列”类算法
5. “递归”类算法
6. “位运算”类算法
7. “字符串”类算法
8. “树”类算法
9. “哈希”类算法
10. “排序”类算法
11. “搜索”类算法
12. “动态规划”类算法
13. “回溯”类算法
14. “数值分析”类算法