leetcode 删除单链表指定元素

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

Supposed the linked list is 1 -> 2 -> 3 -> 4 and you are given the third node with value 3, the linked list should become 1 -> 2 -> 4 after calling your function.

一开始想到的是已经知道删除节点p之前的节点q,那么:

q->next=p->next;
delete p;

但是题目很明显只给出单链表要删除的节点p,其他信息不知,故不能直接采用上述写法,但是思想还是一致:可以把p下一位值赋给p,然后把p的下一位删除,因为我们已经知道p的下一位的前的节点:

 void deleteNode(struct ListNode* node) {
	 node->val=node->next->val;
	 node->next=node->next->next;
	 //delete p;
}


你可能感兴趣的:(算法区)