题解 | #删除链表的节点#
删除链表的节点
https://www.nowcoder.com/practice/f9f78ca89ad643c99701a7142bd59f5d
/** * struct ListNode { * int val; * struct ListNode *next; * }; */ /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param head ListNode类 * @param val int整型 * @return ListNode类 */ #include <stdlib.h> struct ListNode* deleteNode(struct ListNode* head, int val ) { // write code here // 不分配内存空间会造成非法访问 struct ListNode*temp = ( struct ListNode*) malloc(sizeof(struct ListNode)); temp->next = head; //如果数位于头节点则直接删除 if (head->val == val) { head = head->next; return head; } //不位于头节点,遍历链表 while (temp->next != NULL && temp->next->val != val) { temp = temp->next; } //找到要删除的节点 if ( temp->next->val == val) { temp->next = temp->next->next; } return head; }