代码随想录算法训练营第三天 |203. 移除链表元素 707.设计链表 206.反转链表

203. 移除链表元素

链表的基础操作,增删查改

但是我在按照自己思路操作的时候,出现了很多需要判断的条件,原因是对于链表的操作不够深入,写的代码判断条件特别多

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


struct ListNode* removeElements(struct ListNode* head, int val){
    while(head != NULL &&head->val == val) {
        head = head->next;
    }
     if(head == NULL) {
        return head;
    }
    
    struct ListNode *prenode = head;
    struct ListNode *pnode = head;
    struct ListNode *currentnode = head->next;
    while(head->next != NULL) {
        pnode = head;
        currentnode = head->next;
        while(currentnode != NULL &¤tnode->val == val) {
            currentnode = currentnode->next;
        }
        pnode->next = currentnode;
        head = currentnode;
        if(head == NULL) {
            break;
        } 
    }
    currentnode = prenode;
    if(head == NULL) {
        return prenode;
    }
    if(head->val == val) {
        pnode->next = NULL;
    } else {
        if(prenode != head) {
            pnode->next = head;
        }
    }
    return prenode;

}

后面参考了卡哥的代码随想录思想,把实现的方法重新写了一遍,如下:

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


struct ListNode* removeElements(struct ListNode* head, int val){
    while(head != NULL &&head->val == val) {
        head = head->next;
    }
    struct ListNode *phead = head;
    while(head != NULL &&head->next != NULL) {
        struct ListNode *tmpnode = head->next;
        while(tmpnode != NULL &&tmpnode->val == val) {
            tmpnode = tmpnode->next;
        }
        head->next = tmpnode;
        head = head->next;
    }
    return phead;
}

果然编程思想非常重要,要不然,会漏掉很多逻辑上的场景,而且代码的逻辑也不直观。

LCR 024. 反转链表

反转链表的思路太巧妙了,

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


struct ListNode* reverseList(struct ListNode* head){
    if(head == NULL) {
        return head;
    }
    struct ListNode *pre = NULL;
    struct ListNode *currentnode = head;
    while(currentnode != NULL) {
        struct ListNode *tmp = currentnode->next;
        currentnode->next = pre;
        pre = currentnode;
        currentnode = tmp;
    }
    return pre;

}

你可能感兴趣的:(算法,链表,java)