leetcode系列(39)Remove Nth Node From End of List,Valid Parentheses,Merge Two Sorted Lists

来源:互联网 发布:阴上买入指标公式源码 编辑:程序博客网 时间:2024/06/15 02:34

这三个题目都是easy难度,也比较简单,这里一并讲了。

Remove Nth Node From End of List:需要计算链表的长度,并且判断n是否有效(题目中直接告诉了n有效)

Valid Parentheses:用一个栈保存左符合'(',‘{’,‘[',遇到右符号则和栈顶比较,如果不match或者栈为空则返回false

Merge two Sorted Lists:递归非常方便的搞定


/** * Definition for singly-linked list. * struct ListNode { *     int val; *     ListNode *next; *     ListNode(int x) : val(x), next(NULL) {} * }; */class Solution {public:    ListNode* removeNthFromEnd(ListNode* head, int n) {        if (head == nullptr || n <= 0) {            return head;        }                int len = _len(head);        ListNode dummy_node(0);        dummy_node.next = head;        auto ptr = &dummy_node;                for (int i = 0; i < (len - n); ++i) {            ptr = ptr->next;        }        auto tmp = ptr->next;        ptr->next = tmp->next;        delete tmp;                return dummy_node.next;    }private:    int _len(ListNode* head) {        int cnt = 0;        while (head) {            ++cnt;            head = head->next;        }        return cnt;    }};class Solution {public:    bool isValid(string s) {        std::stack<char> stc_;        for (auto item : s) {            if (item == '(' || item == '{' || item == '[') {                stc_.push(item);            } else {                if (stc_.empty()) {                    return false;                } else {                    if (_is_match(item, stc_.top())) {                        stc_.pop();                    } else {                        return false;                    }                }            }        }                return stc_.empty();    }    private:    bool _is_match(char c1, char c2) {        if (c1 == ')') {            return c2 == '(';        } else if (c1 == ']') {            return c2 == '[';        } else {            return c2 == '{';        }    }};/** * Definition for singly-linked list. * struct ListNode { *     int val; *     ListNode *next; *     ListNode(int x) : val(x), next(NULL) {} * }; */class Solution {public:    ListNode* mergeTwoLists(ListNode* head1, ListNode* head2) {        ListNode* head = nullptr;        if (head1 == nullptr) {            head = head2;        } else if (head2 == nullptr) {            head = head1;        } else {            if (head1->val < head2->val) {                head = head1;                head->next = mergeTwoLists(head1->next, head2);            } else {                head = head2;                head->next = mergeTwoLists(head1, head2->next);            }        }        return head;    }};


1 0