题解 | #删除链表的节点#

删除链表的节点

http://www.nowcoder.com/practice/f9f78ca89ad643c99701a7142bd59f5d

//返回值有3种情况,空,头结点,非头结点。
struct ListNode* deleteNode(struct ListNode* head, int val ) { 
    if(head == NULL)  
        return NULL;   //空链表找个毛线
    if(head->val == val)
        return head->next;   //返回的是非头结点的情况
    struct ListNode* pre = head;
    struct ListNode* p = head->next;
    while(p != NULL){
         if(p->val != val){
             pre = p;   //先移动前驱
             p = p->next;  //再移动工作结点,否则会断链
         }
         else{  //找到要找的元素,就跳过该结点,结束
             pre->next = pre->next->next;
             break;
         }        
    } 
    return head;
}

全部评论

相关推荐

评论
点赞
1
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务