链表理论基础
链表的定义
//单链表
struct ListCode{
int val; //节点上存储的元素
ListNode *next; //指向下一个节点的指针
ListNode(int x) :val(x), next(NULL) {} //节点的构造函数
};
//通过自己定义构造函数初始化节点:
ListNode* head = new Listnode(5);
//使用默认构造函数初始化节点
ListNode* head = new ListNode();
head->val = 5;
Leetcode 203 移除链表元素
由于删除第一个节点和最后一个节点,和普通节点的移除方法不一样
一般方法:需要区分头节点和其他节点
if (head != NULL && head -> next == traget){ //如果头节点不为空且头节点为目标值
head = head -> next; //删除头节点
}
while (head != NULL && head -> next == traget){ //如果头节点不为空且头节点为目标值
head = head -> next; //删除头节点
cur = head; //定义临时指针
while(cur != NULL && cur -> next != NULL && ) {
if(cur -> next == target)
cur -> next = cur->next->next;
else
cur = cur->next;
}
return head;
class Solution {
public:
ListNode* removeElements(ListNode* head, int val) {
// 删除头结点
while (head != NULL && head->val == val) { // 注意这里不是if
ListNode* tmp = head;
head = head->next;
delete tmp;
}
// 删除非头结点
ListNode* cur = head;
while (cur != NULL && cur->next!= NULL) {
if (cur->next->val == val) {
ListNode* tmp = cur->next;
cur->next = cur->next->next;
delete tmp;
} else {
cur = cur->next;
}
}
return head;
}
};
设置虚拟节点
Leetcode 707 设计链表
这道题目设计链表的五个接口:
- 获取链表第index个节点的数值
- 在链表的最前面插入一个节点
- 在链表的最后面插入一个节点
- 在链表第index个节点前面插入一个节点
- 删除链表的第index个节点
Leetcode 206 反转链表
1、首先定义一个cur指针,指向head;
2、再定义一个pre指针,初始化为null。
开始反转:
3、 首先将cur->next用tmp指针保存一下,保存这个节点
4、将cur->next指向pre
5、循环走如下代码逻辑了,继续移动pre和cur指针
6、cur 指针已经指向了null,循环结束,eturn pre指针就可以
/**
* 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* tmp; //初始化tmp,用于临时保存cur->next
ListNode* pre = NULL; //初始化pre为NULL
ListNode* cur = head; //初始化cur为head
while(cur)
{
tmp = cur->next; //将tmp = cur->next
cur->next = pre; //将cur->next = pre
pre = cur; //将pre为下一个cur
cur = tmp; //将cur为下一个tmp
}
return pre;
}
};