[leetcode]237.Delete Node in a Linked List
阿新 • • 發佈:2018-10-14
pub fun acc like exc class 解法 不同 處理方法
題目
Write a function to delete a node (except the tail) in a singly linked list, given only access to that node.
Given linked list -- head = [4,5,1,9], which looks like following:
4 -> 5 -> 1 -> 9
解法
思路
題目沒看懂系列。。。
這道題讓我們刪除鏈表的一個節點,更通常不同的是,沒有給我們鏈表的起點,只給我們了一個要刪的節點,跟我們以前遇到的情況不太一樣,我們之前要刪除一個節點的方法是要有其前一個節點的位置,然後將其前一個節點的next連向要刪節點的下一個,然後delete掉要刪的節點即可。這道題的處理方法是先把當前節點的值用下一個節點的值覆蓋了,然後我們刪除下一個節點即可,代碼如下:
代碼
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public void deleteNode(ListNode node) {
node.val=node.next.val;
node.next=node.next.next;
}
}
[leetcode]237.Delete Node in a Linked List