203.移除链表元素
链接——链接
class Solution {
public:
ListNode* removeElements(ListNode* head, int val) {
if(!head)
{
return head;
}
//设置一个新的头结点指向head——就能解决
ListNode* Newhead = new ListNode;
Newhead->next = head;
ListNode* tempnode = Newhead;
while(tempnode->next)
{
if(tempnode->next->val == val)
{
ListNode* recv = tempnode->next;
tempnode->next= tempnode->next->next;
delete recv;
}
else
{
tempnode = tempnode->next;
}
}
ListNode* temp = Newhead->next;
delete Newhead;
return temp;
}
};
234.回文链表
题目——链接
class Solution {
public:
bool isPalindrome(ListNode* head) {
//用容器装,然后从头到后遍历比较
//注意容器存储类型,存val内存开销会小一点
vector<int>ListV;
while(head)
{
ListV.push_back(head->val);
head = head->next;
}
for(int i = 0,j= ListV.size()-1;i<j;i++,j--)
{
if(ListV[i]!= ListV[j])
{
return false;
}
}
return true;
}
};
237.删除链表中的结点
题目——链接
//将变成后面的结点,然后将后面的结点删除防止内存泄漏
class Solution {
public:
void deleteNode(ListNode* node) {
ListNode* tempnode = node->next;
node->val = tempnode->val;
node->next = tempnode->next;
delete tempnode;
}
};