代码随想录算法训练营第三天

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

203.移除链表元素

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    ListNode* removeElements(ListNode* head, int val) {
        while(head != NULL && head->val == val){
            head = head-> next;
        }
        ListNode * cur;
        cur = head;
        while(cur != NULL && cur->next != NULL){
            if(cur->next->val == val){
                cur->next = cur->next->next;
            }
            else{
                cur = cur->next;
            }
        }
        return head;
    }
};

总结:

  1. 对于指针类型的对象,必须使用 -> 来访问其成员;而对于非指针类型的对象,则需要使用.
  2. 注意判断条件不要只写cur != NULL,要写cur != NULL && cur->next != NULL

707.设计链表

大二刚开始学数据结构,第一节课就是写的这个。 期末考试也背了好久。不想再写了。

206.反转链表

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    ListNode* reverseList(ListNode* head) {
        ListNode * cur = head;
        ListNode * pre = NULL;
        ListNode * temp;
        while(cur != NULL){
            temp = cur -> next;
            cur -> next = pre;
            pre =cur;
            cur = temp;
        }
        return pre;
    }
};

看懂了就没啥难度。

代码随想录算法训练 文章被收录于专栏

代码随想录算法训练

全部评论

相关推荐

ResourceUtilization:四六级不愧是大学最有用的证之一
点赞 评论 收藏
分享
04-18 15:58
已编辑
门头沟学院 设计
kaoyu:这一看就不是计算机的,怎么还有个排斥洗碗?
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务