leetcode237~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.

刪除一個節點,這題確實很簡單,但乍一看可能沒啥思路。只給出一個節點,而且要刪除這個節點,常見的是找到前驅,然後讓前驅的next指向要刪除節點的下一個節點即可。這裏頭節點都沒給出,顯然不能這樣做。
一個節點只能獲取到下一個節點的信息,故採用了值替換。

public void deleteNode(ListNode node) {
        if(node.next==null) {
            return;
        }
       node.val = node.next.val;
       node.next = node.next.next;
    }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章