當前位置:
首頁 >
Leet Code OJ 237. Delete Node in a Linked List [Difficulty: Easy]
發布時間:2024/2/28
32
豆豆
生活随笔
收集整理的這篇文章主要介紹了
Leet Code OJ 237. Delete Node in a Linked List [Difficulty: Easy]
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
題目:
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.
翻譯:
寫一個方法去刪除單鏈表的一個節點(非尾節點),只給出訪問這個節點的參數。
假定鏈表是1 -> 2 -> 3 -> 4,給你的節點是第三個節點(值為3),這個鏈表在調用你的方法后應該變為 1 -> 2 -> 4。
分析:
刪除鏈表的節點的常規做法是修改上一個節點的next指針。然而這邊并沒有提供上一個節點的訪問方式,故轉變思路改為刪除下一節點,直接將下一個節點的val和next賦值給當前節點。
代碼:
/*** 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;} }總結
以上是生活随笔為你收集整理的Leet Code OJ 237. Delete Node in a Linked List [Difficulty: Easy]的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Leet Code OJ 112. Pa
- 下一篇: Leet Code OJ 171. Ex