剑指 Offer 18:删除链表的节点

This commit is contained in:
huangge1199 2021-06-07 13:16:40 +08:00
parent d3f1c85427
commit a893dd6a8b
2 changed files with 102 additions and 0 deletions

View File

@ -0,0 +1,73 @@
//给定单向链表的头指针和一个要删除的节点的值定义一个函数删除该节点
//
// 返回删除后的链表的头节点
//
// 注意此题对比原题有改动
//
// 示例 1:
//
// 输入: head = [4,5,1,9], val = 5
//输出: [4,1,9]
//解释: 给定你链表中值为 5 的第二个节点那么在调用了你的函数之后该链表应变为 4 -> 1 -> 9.
//
//
// 示例 2:
//
// 输入: head = [4,5,1,9], val = 1
//输出: [4,5,9]
//解释: 给定你链表中值为 1 的第三个节点那么在调用了你的函数之后该链表应变为 4 -> 5 -> 9.
//
//
//
//
// 说明
//
//
// 题目保证链表中节点的值互不相同
// 若使用 C C++ 语言你不需要 free delete 被删除的节点
//
// Related Topics 链表
// 👍 137 👎 0
package leetcode.editor.cn;
import com.code.leet.entiy.ListNode;
//剑指 Offer 18:删除链表的节点
public class ShanChuLianBiaoDeJieDianLcof{
public static void main(String[] args) {
//测试代码
Solution solution = new ShanChuLianBiaoDeJieDianLcof().new Solution();
}
//力扣代码
//leetcode submit region begin(Prohibit modification and deletion)
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode deleteNode(ListNode head, int val) {
ListNode temp = head;
ListNode pro = head;
while (temp.val == val) {
head = pro = temp = head.next;
}
temp = temp.next;
while (temp != null) {
if (temp.val == val) {
pro.next = temp.next;
}else{
pro = temp;
}
temp = temp.next;
}
return head;
}
}
//leetcode submit region end(Prohibit modification and deletion)
}

View File

@ -0,0 +1,29 @@
<p>给定单向链表的头指针和一个要删除的节点的值,定义一个函数删除该节点。</p>
<p>返回删除后的链表的头节点。</p>
<p><strong>注意:</strong>此题对比原题有改动</p>
<p><strong>示例 1:</strong></p>
<pre><strong>输入:</strong> head = [4,5,1,9], val = 5
<strong>输出:</strong> [4,1,9]
<strong>解释: </strong>给定你链表中值为&nbsp;5&nbsp;的第二个节点,那么在调用了你的函数之后,该链表应变为 4 -&gt; 1 -&gt; 9.
</pre>
<p><strong>示例 2:</strong></p>
<pre><strong>输入:</strong> head = [4,5,1,9], val = 1
<strong>输出:</strong> [4,5,9]
<strong>解释: </strong>给定你链表中值为&nbsp;1&nbsp;的第三个节点,那么在调用了你的函数之后,该链表应变为 4 -&gt; 5 -&gt; 9.
</pre>
<p>&nbsp;</p>
<p><strong>说明:</strong></p>
<ul>
<li>题目保证链表中节点的值互不相同</li>
<li>若使用 C 或 C++ 语言,你不需要 <code>free</code><code>delete</code> 被删除的节点</li>
</ul>
<div><div>Related Topics</div><div><li>链表</li></div></div>\n<div><li>👍 137</li><li>👎 0</li></div>