您好,欢迎来到乌哈旅游。
搜索
您的当前位置:首页LeetCode之Delete Node in a Linked List (Java+C)

LeetCode之Delete Node in a Linked List (Java+C)

来源:乌哈旅游

题意: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.

意思是:删除单向链表中的某一节点
但是!题目给的参数很有意思,只是给了需要删除的那个节点,而不是整个链表和需要被删除节点的索引

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) return;
        node.val = node.next.val;
        node.next = node.next.next;
    }
}

C代码:

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */
void deleteNode(struct ListNode* node) {
    node->val = node->next->val;
    node->next = node->next->next;
}

解题思路:既然只提供了一个要删的节点,那么先把当前节点的值用下一个节点的值覆盖了,然后我们删除下一个节点即可

因篇幅问题不能全部显示,请点此查看更多更全内容

Copyright © 2019- wuhaninfo.cn 版权所有

违法及侵权请联系:TEL:199 1889 7713 E-MAIL:2724546146@qq.com

本站由北京市万商天勤律师事务所王兴未律师提供法律服务