struct ListNode* removeElements(struct ListNode* head, int val) { struct ListNode * tmp = (struct ListNode *)malloc(sizeof(struct ListNode)); struct ListNode * pre = tmp; pre->next = head; while(head != NULL) { if(head->val == val) { head= head->next; pre->next = head; }else{ head = head->next; pre = pre->next; } } return tmp->next; }
基本思路:
在删某个节点的时候需要修改该节点前面节点的next指针,所以需要有一个pre指针
另外需要有个节点来保存节点最初的位置 。
struct ListNode* removeElements(struct ListNode* head, int val)
{
struct ListNode * tmp = (struct ListNode *)malloc(sizeof(struct ListNode));
struct ListNode * pre = tmp;
pre->next = head;
while(head != NULL)
{
if(head->val == val) {
head= head->next;
pre->next = head;
}else{
head = head->next;
pre = pre->next;
}
}
return tmp->next;
}
时间: 2024-12-14 18:38:25