203.移除链表元素
知识点:链表 状态:半个小时憋出来的
思路:生成一个新节点在头节点前,他的指针是*newhead,在设置一个*r=newhead,r就是用来遍历链表的,每次比较r->next->val与val,如果相等,则跳过这个节点。
注意:头节点是真实存在的节点,注意区分头指针和头节点。
class Solution {
public:
ListNode* removeElements(ListNode* head, int val)
{
ListNode * newhead =new ListNode(0, head); // 建立一个新的节点,放在头节点前,newhead为指向它的指针,也就是最后返回的
ListNode * r = newhead; // 向后处理的指针,负责移动
while(r->next != NULL)
{
if(r->next->val == val)
{
r->next =r ->next->next;
}
else
{
r=r->next;
}
}
return newhead->next;
}
};
![](https://img-blog.csdnimg.cn/8a9c1a3b23574e5c8ccf2474f4e91f36.png)
707.设计链表
知识点:链表 状态:太复杂了到处都是错,细节很多
思路:私有成员为虚拟头节点dummynode和长度size,每次插入或者删除时都要更新size,注意区是找第i个节点还是位置为i。
class MyLinkedList {
public:
struct LinkedNode {
int val;
LinkedNode* next;
LinkedNode(int val):val(val), next(nullptr){}
};
MyLinkedList()
{
_dummyHead = new LinkedNode(0);
_size = 0;
}
int get(int index)
{
if ( index < 0 || index > (_size-1) )
{return -1;}
else
{
LinkedNode * cur = _dummyHead ->next;
while ( index--)
{
cur = cur -> next;
}
return cur->val;
}
}
void addAtHead(int val)
{
LinkedNode * temp = new LinkedNode(val);
temp->next = _dummyHead->next;
_dummyHead ->next =temp;
_size++;
}
void addAtTail(int val)
{
LinkedNode * cur = _dummyHead;
LinkedNode * temp = new LinkedNode(val);
while(cur ->next != NULL)
{
cur=cur->next;
}
cur->next =temp;
_size++;
}
void addAtIndex(int index, int val)
{
if (index > _size) {
return;
}
LinkedNode* temp = new LinkedNode(val);
LinkedNode* cur = _dummyHead;
while(index--) {
cur = cur->next;
}
temp->next = cur->next;
cur->next = temp;
_size++;
}
void deleteAtIndex(int index)
{
if ( _size <= index )
{return;}
else
{
LinkedNode* cur = _dummyHead;
while(index--)
{
cur = cur -> next;
}
cur ->next = cur -> next ->next;
_size--;
}
}
void printLinkedList()
{
LinkedNode* cur = _dummyHead;
while (cur->next != nullptr)
{
cout << cur->next->val << " ";
cur = cur->next;
}
cout << endl;
}
private:
int _size = 0;
LinkedNode * _dummyHead;
};
/**
* 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);
*/
![](https://img-blog.csdnimg.cn/d04dbd85a2544724a016f3ba6efecef1.png)
206.反转链表
知识点:链表 状态:双指针之前做过
思路:两个指针,left初始为null,right为head,当right不为空时,将right指向left,然后left移动到right,right变成right->next。
注意:返回的是left!!!!返回right的话为空,因为此时right就是最后一个结点的next(null)
class Solution {
public:
ListNode* reverseList(ListNode* head)
{
ListNode * left = NULL;
ListNode * right = head;
while (right != NULL)
{
ListNode * temp = right->next;
right->next = left;
left = right;
right = temp;
}
return left;
}
};
![](https://img-blog.csdnimg.cn/a15064db77794485b07e1f3a894ef277.png)