代码随想录算法训练营第三天 | 203.移除链表元素 ,707.设计链表 ,206.反转链表
1.1 203.移除链表元素
思路:
- 需要考虑当前的指针位置,从而进行判断处理
- 最终返回头结点,可以通过dummyHead进行返回
class Solution {
public:
ListNode* removeElements(ListNode* head, int val) {
ListNode* dummyHead = new ListNode();
ListNode* cur = new ListNode();
dummyHead -> next = head;
cur = dummyHead;
while(cur -> next){
if(cur->next->val == val){
cur->next = cur->next->next;
}
else cur = cur -> next;
}
return dummyHead->next;
}
};
1.2 707.设计链表
思路:
- 初始化的时候维护
_dummyHead
和_size
class MyLinkedList {
public:
struct ListNode{
int val;
ListNode* next;
ListNode(int x): val(x), next(nullptr){}
};
MyLinkedList() {
_dummyHead = new ListNode(0);
_size = 0;
}
int get(int index) {
if(index < 0 || index > _size-1) return -1;
ListNode* cur = _dummyHead->next;
while(index--){
cur = cur->next;
}
return cur->val;
}
void addAtHead(int val) {
ListNode* newNode = new ListNode(val);
newNode->next = _dummyHead->next;
_dummyHead->next = newNode;
_size++;
}
void addAtTail(int val) {
ListNode* newNode = new ListNode(val);
ListNode* cur = _dummyHead;
while(cur->next){
cur = cur->next;
}
cur->next = newNode;
_size++;
}
void addAtIndex(int index, int val) {
if(_size < index) return;
ListNode* newNode = new ListNode(val);
ListNode* cur = _dummyHead;
while(index--){
cur = cur->next;
}
newNode->next = cur->next;
cur->next = newNode;
_size++;
}
void deleteAtIndex(int index) {
if(index < 0 || index > _size-1) return;
ListNode* cur = _dummyHead;
while(index--){
cur = cur->next;
}
cur->next = cur->next->next;
_size--;
}
private:
int _size;
ListNode* _dummyHead;
};
1.3 206.反转链表
思路:
- 需要一个值存放下一节点的信息
- 注意首位最后的处理
class Solution {
public:
ListNode* reverseList(ListNode* head) {
if(head == nullptr || head->next == nullptr) return head;
ListNode *pre = head;
ListNode *cur = head->next;
while(cur != nullptr){
ListNode *temp = cur->next;
cur->next = pre;
pre = cur;
cur = temp;
}
head->next = nullptr;
return pre;
}
};