LeetCode-203-移除链表元素-C语言

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */

typedef struct ListNode Node;

/*
 * 算法思想:
 * 将符合条件的节点,添加到一个新链表中,返回新链表
 *
 */

struct ListNode* removeElements(struct ListNode* head, int val){
    Node node;
    node.next = NULL;
    Node *rear = &node;
    Node *last = NULL;
    
    while(head || last){
        if(last && last->val != val){
            rear->next = last;
            rear = rear->next;
            last->next = NULL;
        }else if(last && last->val == val){
            free(last);
            last = NULL;
        }
        
        
        last = head;
        if(head)
            head = head->next;
    }

    
    return node.next;
}




猜你喜欢

转载自blog.csdn.net/weixin_36094222/article/details/90046897