剑指 Offer 18. 删除链表的节点
剑指 Offer 18. 删除链表的节点
问题描述:
给定单向链表的头指针和一个要删除的节点的值,定义一个函数删除该节点。
返回删除后的链表的头节点。
注意:此题对比原题有改动
示例 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 被删除的节点
/**
* Definition for singly-linked list.
* class ListNode(var _x: Int = 0) {
* var next: ListNode = null
* var x: Int = _x
* }
*/
object Solution {
def deleteNode(head: ListNode, value: Int): ListNode = {
val dummyHead = new ListNode()
dummyHead.next = head
var pre = dummyHead
var cur = head
while (cur != null) {
if (cur.x == value) {
val temp = cur.next
pre.next = temp
cur = temp
//仅存在唯一的去除节点
return dummyHead.next
} else {
pre = pre.next
cur = cur.next
}
}
return dummyHead.next
}
}
/**
* Definition for singly-linked list.
* type ListNode struct {
* Val int
* Next *ListNode
* }
*/
func deleteNode(head *ListNode, val int) *ListNode {
if head == nil {return head}
if head.Val == val {return head.Next}
dummyHead := &ListNode{Val: 0, Next: head}
pre := dummyHead
cur := head
for (cur != nil) {
if cur.Val == val {
temp := cur.Next
pre.Next = temp
cur = temp
return dummyHead.Next
} else {
pre = pre.Next
cur = cur.Next
}
}
return dummyHead.Next
}