前言
欢迎大家积极在评论区留言发表自己的看法,知无不言,言无不尽,养成每天刷题的习惯,也可以自己发布优质的解题报告,供社区一同鉴赏,吸引一波自己的核心粉丝。
今天是七月集训第十二天:链表🔥🔥🔥
一、练习题目
二、算法思路
- 1、707. 设计链表:🔥🔥链表的增删改查,十分值得一做,练一练基本功。
- 2、2326. 螺旋矩阵 IV:🔥🔥这题59. 螺旋矩阵 II做法相似,不过一个数组一个是链表,可以先从前面的题目看起。
三、源码剖析
// 707. 设计链表
class MyLinkedList {
struct Node {
int val;
Node *next = NULL;
Node() {next = NULL;}
Node(int v) : val(v), next(NULL) {}
};
Node *dummyhead;
public:
MyLinkedList() {
dummyhead = new Node();
}
int get(int index) {
Node *now = dummyhead;
for(int i = 0; i <= index; ++i) {
now = now->next;
if(now == NULL) {
return -1;
}
}
return now->val;
}
// 头插
void addAtHead(int val) {
Node *n = new Node(val);
Node *nnext = dummyhead->next;
dummyhead->next = n;
n->next = nnext;
}
// 尾插
void addAtTail(int val) {
Node *n = new Node(val);
Node *now = dummyhead;
while(now->next) {
now = now->next;
}
now->next = n;
}
void addAtIndex(int index, int val) {
Node *n = new Node(val);
Node *now = dummyhead;
if(index < 0) {
addAtHead(val);
return;
}
for(int i = 0; i < index; ++i) {
now = now->next;
if(now == NULL) {
return;
}
}
Node *nnext = now->next;
now->next = n;
n->next = nnext;
}
void deleteAtIndex(int index) {
if(get(index) == -1) {
return;
}
Node *now = dummyhead;
for(int i = 0; i < index; ++i) {
now = now->next;
}
now->next = now->next->next;
}
};
- 1、链表的增删改查,同时要注意链表的下标从0开始的。
// 2326. 螺旋矩阵 IV
class Solution {
int dir[4][2]={{0, 1},{1, 0},{0, -1,},{-1, 0}};
bool hash[100010];
public:
vector<vector<int>> spiralMatrix(int m, int n, ListNode* head) {
memset(hash ,0, sizeof(hash));
vector<vector<int>> ans;
int cnt=0;
for(int i = 0; i<m; ++i) {
vector<int> tmp;
for(int j = 0; j < n; ++j) {
tmp.push_back(-1);
}
ans.push_back(tmp);
}
int d = 0;
int i = 0,j = 0;
while(head) {
int val = head->val;
ans[i][j] = val;
cnt++;
if(cnt == n*m) {
break;
}
hash[i*n+j] = 1;
i += dir[d][0];
j += dir[d][1];
while(i == -1 || j == -1 || i == m || j == n || hash[i * n + j]){
i -= dir[d][0];
j -= dir[d][1];
d = (d+1)%4;
i += dir[d][0];
j += dir[d][1];
}
head = head->next;
}
return ans;
}
};
- 1、螺旋矩阵的遍历问题。