题解 | #删除链表的节点#
判断两种情况。
1.当要删除的结点为开始结点,则返回开始节点的后一个节点。
2.当要删除的结点不是开始结点,则需要把前一个结点的next指针指向要删除结点的后一个结点。
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* ListNode(int x) : val(x), next(nullptr) {}
* };
*/
class Solution {
public:
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param head ListNode类
* @param val int整型
* @return ListNode类
*/
ListNode* deleteNode(ListNode* head, int val) {
// write code here
if (head == nullptr) return head;
ListNode* pre = NULL;
ListNode* cur = head;
while(cur->val != val) {
pre = cur;
cur = cur->next;
}
if (cur == head) return head->next;
pre->next = cur->next;
return head;
}
};
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
#
# 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
#
#
# @param head ListNode类
# @param val int整型
# @return ListNode类
#
class Solution:
def deleteNode(self , head: ListNode, val: int) -> ListNode:
# write code here
if head is None:
return head
pre = None
cur = head
while cur.val != val:
pre = cur
cur = cur.next
if cur == head:
return head.next
pre.next = cur.next
return head