#203.移除链表元素
虚拟头节点 方便删除 判断cur->next是否为空
class MyLinkedList {
public:
struct LinkNode {
int val;
LinkNode *next;
LinkNode(int v):val(v),next(NULL){};
}; //struct 注意分号
MyLinkedList() {
//声明虚拟头节点?
virhead=new LinkNode(0);
_size=0;
}
int get(int index) {
if( index<0 || index>(_size-1))
{
return -1;
}
LinkNode *cur=virhead->next;
while(index--)
{
cur=cur->next;
}
return cur->val;
}
void addAtHead(int val) {
LinkNode *node=new LinkNode(val);
node->next=virhead->next;
virhead->next=node;
//大小要增加
_size++;
}
void addAtTail(int val) {
LinkNode *node=new LinkNode(val);
LinkNode *cur=virhead;
while(cur->next!=NULL)
{
cur=cur->next;
}
cur->next=node;
_size++;
}
void addAtIndex(int index, int val) {
LinkNode *cur=virhead;
LinkNode *node=new LinkNode(val);
if(index>_size)
{
return;
}
while(index--)
{
cur=cur->next;
}
node->next=cur->next;
cur->next=node;
_size++;
}
void deleteAtIndex(int index) {
if(index<0||index>=_size)
{
return ;
}
LinkNode *cur=virhead;
while(index--)
{
cur=cur->next;
}
cur->next=cur->next->next;
_size--;
}
private:
int _size;
LinkNode* virhead;
};
/**
* Your MyLinkedList object will be instantiated and called as such:
* MyLinkedList* obj = new MyLinkedList();
* int param_1 = obj->get(index);
* obj->addAtHead(val);
* obj->addAtTail(val);
* obj->addAtIndex(index,val);
* obj->deleteAtIndex(index);
*/
206.反转链表
两个节点 一个前一个后 修改后的next指向前 注意顺序 先翻转再更新
class Solution {
public:
ListNode* reverseList(ListNode* head) {
ListNode *cur=head;
ListNode *pre=nullptr;
ListNode*tmp;
while(cur!=nullptr)
{
tmp=cur->next;
//先翻转
cur->next=pre;
pre=cur;
cur=tmp;
}
//最后返回的是pre
return pre;
}
};
就是交换相邻的两个节点 分三个步骤
开始要存储虚拟头节点下的第一个节点和第三个节点
class Solution {
public:
ListNode* swapPairs(ListNode* head) {
ListNode *virhead=new ListNode(0);
virhead->next=head;
//这里cur指向的虚拟头节点 不是真正的head
ListNode *cur=virhead;
//判断条件 下面的两个节点都必须存在
while(cur->next!=nullptr&&cur->next->next!=nullptr)
{
ListNode* tmp1=cur->next;
ListNode* tmp3=cur->next->next->next;
cur->next=cur->next->next;
cur->next->next=tmp1;
cur->next->next->next=tmp3;
//最后要移动两位
cur=cur->next->next;
}
return virhead->next;
}
};
19.删除链表的倒数第N个节点
双指针法
fast先往前移动n单位 然后两个指针遍历到最后
两个指针中间就是要删除的节点
class Solution {
public:
ListNode* removeNthFromEnd(ListNode* head, int n) {
ListNode *virhead=new ListNode(0);
virhead->next=head;
//指向的是虚拟头节点
ListNode* slow=virhead;
ListNode* fast=virhead;
//判断条件 要加上fast 本身不等于null 最后一个元素也要考虑
while(n--&&fast!=nullptr)
{
fast=fast->next;
}
fast=fast->next;
//判断条件 fast 本身不等于null 最后一个元素也要考虑
while(fast!=nullptr)
{
slow=slow->next;
fast=fast->next;
}
slow->next=slow->next->next;
return virhead->next;
}
};
找公共区间