[Java]LeetCode237. 刪除鏈表中的節點 | Delete Node in a Linked List

★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公衆號:山青詠芝(shanqingyongzhi)
➤博客園地址:山青詠芝(https://www.cnblogs.com/strengthen/
➤GitHub地址:https://github.com/strengthen/LeetCode
➤原文地址:http://www.javashuo.com/article/p-dlyqvani-mc.html 
➤若是連接不是山青詠芝的博客園地址,則多是爬取做者的文章。
➤原文已修改更新!強烈建議點擊原文地址閱讀!支持做者!支持原創!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★html

Write a function to delete a node (except the tail) in a singly linked list, given only access to that node.node

Given linked list -- head = [4,5,1,9], which looks like following:git

Example 1:github

Input: head = [4,5,1,9], node = 5
Output: [4,1,9]
Explanation: You are given the second node with value 5, the linked list should become 4 -> 1 -> 9 after calling your function.

Example 2:微信

Input: head = [4,5,1,9], node = 1
Output: [4,5,9]
Explanation: You are given the third node with value 1, the linked list should become 4 -> 5 -> 9 after calling your function.

Note:函數

  • The linked list will have at least two elements.
  • All of the nodes' values will be unique.
  • The given node will not be the tail and it will always be a valid node of the linked list.
  • Do not return anything from your function.

請編寫一個函數,使其能夠刪除某個鏈表中給定的(非末尾)節點,你將只被給定要求被刪除的節點。spa

現有一個鏈表 -- head = [4,5,1,9],它能夠表示爲:code

    4 -> 5 -> 1 -> 9

示例 1:htm

輸入: head = [4,5,1,9], node = 5
輸出: [4,1,9]
解釋: 給定你鏈表中值爲 5 的第二個節點,那麼在調用了你的函數以後,該鏈表應變爲 4 -> 1 -> 9.

示例 2:blog

輸入: head = [4,5,1,9], node = 1
輸出: [4,5,9]
解釋: 給定你鏈表中值爲 1 的第三個節點,那麼在調用了你的函數以後,該鏈表應變爲 4 -> 5 -> 9.

說明:

  • 鏈表至少包含兩個節點。
  • 鏈表中全部節點的值都是惟一的。
  • 給定的節點爲非末尾節點而且必定是鏈表中的一個有效節點。
  • 不要從你的函數中返回任何結果。

0ms

1 class Solution {
2     public void deleteNode(ListNode node) {
3         node.val=node.next.val;
4         node.next=node.next.next;
5     }
6 }

 1 /**
 2  * Definition for singly-linked list.
 3  * public class ListNode {
 4  *     int val;
 5  *     ListNode next;
 6  *     ListNode(int x) { val = x; }
 7  * }
 8  */
 9 class Solution {
10     public void deleteNode(ListNode node) {
11         
12         int temp;
13         temp = node.val;
14         node.val = node.next.val;
15         node.next.val =  temp;
16         
17         node.next = node.next.next;        
18         
19     }
20 }
相關文章
相關標籤/搜索