LeetCode:237. Delete Node in a Linked List

来源:互联网 发布:下载淘宝网到手机桌面 编辑:程序博客网 时间:2024/05/18 17:24

0X01 题目

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.

0X02 题意

题目的要求就是删除链表中的一个元素,给的数据结构是一个单链表。

    public class ListNode {        int val;        ListNode next;        ListNode(int x) {            val = x;        }    }

注意判断一下需要删除的节点是否为空、该节点是否是最后一个节点即可。

0X03 题解

1.解法一(Dante:Java)

比较直观的一个解法,判断一下需要删除的节点是否为空、该节点是否是最后一个节点即可。

  • 时间复杂度O(N)

  • 空间复杂度O(1)

public class Solution {    public void deleteNode(ListNode node) {        if(node == null)            return;        if(node.next == null){            node = null;            return;        }        node.val = node.next.val;        node.next = node.next.next;    }}

2016-08-04 10:50:00 hzct

0 0
原创粉丝点击