203. 移除链表元素
思路:如题,考察链表,因为head也可能被移除,需要设置一下dummy_head,访问链表是通过指针,所以定义链表时记得使用ListNode*,访问内部元素使用->。Leetcode不需要自己定义链表,但是ACM模式就不一样了,所以要熟悉链表定义方式。
题解:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* removeElements(ListNode* head, int val) {
ListNode *dummy_head = new ListNode(0, head);
ListNode *cur = dummy_head;
while (cur -> next != nullptr)
{
ListNode *tmp;
tmp = cur -> next;
if (tmp->val == val)
{
cur -> next = cur -> next -> next;
delete tmp;
}
else
cur = cur -> next;
}
head = dummy_head->next;
delete dummy_head;
return head;
}
};
707. 设计链表
思路:依然考察链表,不难,倒是考察细心程度,记得定义_size方便剪枝。新增节点都用newnode命名,规范一点。
题解:
class MyLinkedList {
public:
struct ListNode{
int val;
ListNode *next;
ListNode(int x) : val(x), next(nullptr){};
};
MyLinkedList() {
_dummy_head = new ListNode(0);
_size = 0;
}
int get(int index) {
if (index >= _size || index < 0)
return -1;
ListNode *cur = _dummy_head -> next;
while(index --)
cur = cur -> next;
return cur -> val;
}
void addAtHead(int val) {
ListNode *newnode = new ListNode(val);
newnode -> next = _dummy_head -> next;
_dummy_head -> next = newnode;
++_size;
}
void addAtTail(int val) {
ListNode *cur = _dummy_head;
ListNode *newnode = new ListNode(val);
while (cur -> next != nullptr)
cur = cur -> next;
cur -> next = newnode;
++_size;
}
void addAtIndex(int index, int val) {
ListNode *cur = _dummy_head;
if (index > _size || index < 0)
return;
while (index --)
cur = cur -> next;
ListNode *newnode = new ListNode(val);
newnode -> next = cur -> next;
cur -> next = newnode;
++_size;
}
void deleteAtIndex(int index) {
if (index >= _size || index < 0)
return;
ListNode *cur = _dummy_head;
while (index --)
cur = cur -> next;
ListNode *tmp = cur -> next;
cur -> next = cur -> next -> next;
delete tmp;
--_size;
}
private:
int _size;
ListNode *_dummy_head;
};
206. 反转链表
思路:搞清楚要存什么就行。每遍历一个到节点,它需要连接到上一个节点,所以需要上一个节点的位置prev,连接完后需要跳转到原本的下一个节点tmp,然后更新prev的位置。
题解:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* reverseList(ListNode* head) {
ListNode *cur = head;
ListNode *prev = nullptr;
while (cur != nullptr)
{
ListNode *tmp = cur -> next;
cur -> next = prev;
prev = cur;
cur = tmp;
}
return prev;
}
};