237. Delete Node in a Linked List
題目:
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.
鏈接:?http://leetcode.com/problems/delete-node-in-a-linked-list/
題解:
沒啥可說的,就是干!
Time Complexity - O(1), Space Complexity - in place
/*** 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) {node.val = node.next.val;node.next = node.next.next;} }?
二刷:
就是改變當前node的val和next節點,都變成下一個節點的值和reference就可以了。
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;}node.val = node.next.val;node.next = node.next.next;} }?
三刷:
唔,這道題我也刷了三遍...
因為不是delete tail,意味著當前節點非空,并且下一個節點非空。 所以我們可以略去一些邊界條件的判斷。
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) {node.val = node.next.val;node.next = node.next.next;} }?
轉載于:https://www.cnblogs.com/yrbbest/p/5003811.html
總結
以上是生活随笔為你收集整理的237. Delete Node in a Linked List的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: iOS开发学无止境 - 这样好用的Rea
- 下一篇: windows server 2008