1. 移除链表元素
【注意】设置虚拟头结点,以免要将头结点与其他节点分别操作
在本题中,我经常忘记delet,以后需要注意。
/**
* 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 *dummyhead = new ListNode(0);
dummyhead->next = head;
ListNode *cur = dummyhead;
while(cur->next != nullptr){
if (cur->next->val == val) {
ListNode *shan = cur->next;
cur->next = cur->next->next;
delete shan;
}
else {
cur = cur->next;
}
}
head = dummyhead->next;
delete dummyhead;
return head;
}
};
2. 设计链表
【注意】删除节点时:
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) {
MyLinkedList();
if (index > (_size - 1) || index < 0) {
return -1;
}
LinkedNode *cur = _dummyhead->next;
while(index--) {
cur = cur->next;
}
return cur->val;
}
void addAtHead(int val) {
addAtIndex(0, val);
}
void addAtTail(int val) {
addAtIndex(_size, val);
}
void addAtIndex(int index, int val) {
if (index > _size || index < 0) {
return;
}
LinkedNode *NewNode = new LinkedNode(val);
LinkedNode *cur = _dummyhead;
while (index--) {
cur = cur->next;
}
NewNode->next = cur->next;
cur->next = NewNode;
_size++;
}
void deleteAtIndex(int index) {
if (index >= _size || index < 0) {
return;
}
LinkedNode *cur = _dummyhead;
while(index--) {
cur = cur->next;
}
LinkedNode *tmp = cur->next;
cur->next = cur->next->next;
delete tmp;
tmp=nullptr;
_size--;
}
private:
int _size;
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);
*/
3. 反转链表
【注意】双指针法
class Solution {
public:
ListNode* reverseList(ListNode* head) {
ListNode *cur = head;
ListNode *pre = nullptr;
ListNode *tmp;
while(cur) {
tmp = cur->next;
cur->next = pre;
pre = cur;
cur = tmp;
}
return pre;
}
};
总的来说,链表的逻辑相对比较简单,对我本人来讲很好吸收。但要牢记链表结构体的定义,在面试如果考到链表题目,得自己写定义。