题解 | #删除链表的节点#
删除链表的节点
https://www.nowcoder.com/practice/f9f78ca89ad643c99701a7142bd59f5d
解题思路
- 先新建一个节点,以便后续对第一个节点进行操作;
- 循环遍历链表,当找到相同的元素的时候就修改链表指针,将目标值移除掉。
复杂度
- 时间复杂度为O(N);
- 空间复杂度为O(1)。
代码
Python
class Solution:
def deleteNode(self , head: ListNode, val: int) -> ListNode:
res = ListNode(-1)
res.next = head
cur = res
while cur.next:
if cur.next.val == val:
cur.next = cur.next.next
break
else:
cur = cur.next
return res.next
C++
class Solution {
public:
ListNode* deleteNode(ListNode* head, int val) {
ListNode* res = new ListNode(-1);
res->next = head;
ListNode* cur = res;
while (cur->next) {
if (cur->next->val == val)
{
cur->next = cur->next->next;
break;
}
else {
cur = cur->next;
}
}
return res->next;
}
};

