19. 删除链表中的倒数第n个节点
/ /双指针的方法
class Solution {
public:
ListNode* removeNthFromEnd(ListNode* head, int n) {
ListNode* cHead = new ListNode(0,head);
ListNode* ptr = cHead;
for(int i=0;i<n;i++)
{
head=head->next;;
}
while(head)
{
ptr=ptr->next;
head=head->next;
}
ptr->next=ptr->next->next;
return cHead->next;
}
};
20. 有效的括号
class Solution {
public:
bool isValid(string s) {
vector<char> stack;
map<char,char> m ={
{'(',')'},
{'[',']'},
{'{','}'}
};
bool ret = false;
for(int i=0;i<s.size();i++)
{
if(s[i]=='('||s[i]=='['||s[i]=='{')
{
stack.push_back(s[i]);
continue;
}
else if(stack.size()==0)
{
return false;
}
else {
char cur = stack.back();
if(m[cur]==s[i]) {
stack.pop_back();
}
else
{
return false;
}
}
}
if(stack.size()==0)
ret = true;
return ret;
}
};
21. 合并两个有序连边
/**
* 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* mergeTwoLists(ListNode* list1, ListNode* list2) {
ListNode* headPtr = new ListNode(0);
ListNode* ptr = headPtr;
while(list1||list2)
{
if(list1&&list2)
{
if(list1->val>list2->val)
{
headPtr->next=list2;
list2=list2->next;
}
else
{
headPtr->next=list1;
list1=list1->next;
}
}
else if (list1)
{
headPtr->next=list1;
list1=list1->next;
}
else
{
headPtr->next=list2;
list2=list2->next;
}
headPtr=headPtr->next;
}
headPtr=ptr->next;
delete ptr;
return headPtr;
}
};