203. 移除链表元素
迭代(虚拟头节点)
class Solution
{
public:ListNode* removeElements(ListNode* head, int val){ListNode* dummyHead = new ListNode(-1, head);ListNode* prev = dummyHead; ListNode* curr = head;while (curr != nullptr){if (curr->val == val){prev->next = curr->next;delete curr;curr = prev->next;}else{prev = curr;curr = curr->next;}}return dummyHead->next;}
};
递归
class Solution
{
public:ListNode* removeElements(ListNode* head, int val){if (head == nullptr){return nullptr;}head->next = removeElements(head->next, val);if (head->val == val){ListNode* temp = head->next;delete head;return temp;}return head;}
};
707. 设计链表
单链表
class MyLinkedList
{
private:class ListNode //链表节点的定义{public:int val;ListNode* next;ListNode() : val(0), next(nullptr) {}ListNode(int x) : val(x), next(nullptr) {}ListNode(int x, ListNode* n) : val(x), next(n) {}};ListNode* head;public:MyLinkedList(): head(nullptr){}int get(int index) {ListNode* ptr = head;while (ptr != nullptr && index >= 1){ptr = ptr->next;index--;}return ptr != nullptr ? ptr->val : -1;}void addAtHead(int val) {addAtIndex(0, val);}void addAtTail(int val){if (head == nullptr){addAtIndex(0, val);return;}ListNode* ptr = head;ListNode* newNode = new ListNode(val, nullptr);while (ptr->next != nullptr){ptr = ptr->next;}ptr->next = newNode;}void addAtIndex(int index, int val){ListNode* prev = nullptr;ListNode* curr = head;while (curr != nullptr && index >= 1){prev = curr;curr = curr->next;index--;}if (index != 0) //index无效{return;}ListNode* newNode = new ListNode(val);if (prev == nullptr) //插入到链表第一个节点之前或者空链表的情况{newNode->next = head;head = newNode;}else //一般情况{prev->next = newNode;newNode->next = curr;}}void deleteAtIndex(int index){ListNode* prev = nullptr;ListNode* curr = head;while (curr != nullptr && index >= 1){prev = curr;curr = curr->next;index--;}if (curr == nullptr) //index无效{return;}else if (prev == nullptr) //删除头节点或者只有一个节点的情况{head = head->next;}else //一般情况{prev->next = curr->next;}delete curr;}
};
206. 反转链表
迭代
class Solution
{
public:ListNode* reverseList(ListNode* head){if (head == nullptr || head->next == nullptr){return head;}ListNode* prev = nullptr;ListNode* curr = head;while (curr != nullptr){ListNode* next = curr->next;curr->next = prev;prev = curr;curr = next;}return prev;}
};
递归
class Solution
{
public:ListNode* reverseList(ListNode* head){if (head == nullptr || head->next == nullptr){return head;}ListNode* newHead = reverseList(head->next);head->next->next = head;head->next = nullptr;return newHead;}
};