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 -> 4after calling your function.

題意:寫一個函數來刪除一個單鏈表中的一個節點(除了尾部),只訪問該節點。就是在不知道頭指針的情況下刪除指定節點

思路:讓指定節點的值等於它的下一個節點的值;然後將該指定節點的指針指向它的下下個節點。

**
 * 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;
    }
}


發佈了97 篇原創文章 · 獲贊 4 · 訪問量 3萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章