- 剑指Offer18.删除链表的节点
- 解题思路
- 代码
可以用一个带哨兵位的头节点作为链表的头。把不等于该值的节点尾插到新链表的后面。最后释放该哨兵节点。
代码struct ListNode* deleteNode(struct ListNode* head, int val){
struct ListNode *phead=(struct ListNode*)malloc(sizeof(struct ListNode));
struct ListNode *tail=phead;
phead->next=NULL;
struct ListNode* cur=head;
while(cur)
{
if(cur->val==val)
{
struct ListNode* temp=cur->next;
free(cur);
cur=temp;
}
else
{
tail->next=cur;
cur=cur->next;
tail=tail->next;
}
}
//最后这里要制成空
tail->next=NULL;
struct ListNode* newhead=phead->next;
free(phead);
return newhead;
}



