当前位置:网站首页>Leetcode -- linked list
Leetcode -- linked list
2022-06-24 09:20:00 【Rain curtain】
Linked list : Single chain list 、 Double linked list 、 Circular linked list .
The difference between linked list and array :
| add to / Delete | lookup | Applicable scenario | |
| Array | O(n) | O(1) | The data is fixed , Search frequently , Less additions and deletions |
| Linked list | O(1) | O(n) | Data is not fixed , Add and delete frequently , Search less |
203 Remove linked list elements
c++ Use the linked list to delete the elements delete Memory space of this element
Method 1 : If the header node is an element that needs to be deleted , Need to put head = head->next
ListNode* removeElements(ListNode* head, int val) {
//val Is the head node element
while (head != NULL && head->val == val)
{
ListNode* tmp = head;
head = head->next;
delete tmp;
}
ListNode* p = head;
//val Not a header node element
while(p != NULL && p->next != NULL){
if(p->next->val == val){
ListNode* tmp = p->next;
p->next = p->next->next;
delete tmp;
}else{
p = p->next;
}
}
return head;
}Method 2 : Set up a virtual head node ( It needs to be initialized ), Let the virtual head node next = head, Finally, remember to let head = Of the virtual head node next, Then delete the virtual head node
ListNode* removeElements(ListNode* head, int val) {
// Set up a virtual head node
ListNode* dummyHead = new ListNode(0);
dummyHead->next = head;
ListNode* p = dummyHead; //p Is the currently accessed node
while(p->next != NULL){
if(p->next->val == val){
ListNode* tmp = p->next;
p->next = p->next->next;
delete tmp;
}else{
p = p->next;
}
}
// Finally, delete the set virtual head node
head = dummyHead->next;
delete dummyHead;
return head;
}707 Design the list
For array traversal, you only need to know its length , The length of the linked list is unknown , You can only find one node at a time , Until... Of a node next = null
class MyLinkedList {
public:
// Define linked list node structure
struct LinkedNode {
int val;
LinkedNode* next;
LinkedNode(int val):val(val), next(nullptr){}
};
// Initialize linked list
MyLinkedList() {
_dummyHead = new LinkedNode(0); // The head node defined here It's a virtual head node , Instead of the real chain header node
_size = 0;
}
// Get to page No index Node values , If index It's illegal. It's returned directly -1, Be careful index It's from 0 At the beginning , The first 0 The first node is the head node
int get(int index) {
if (index > (_size - 1) || index < 0) {
return -1;
}
LinkedNode* cur = _dummyHead->next;
while(index--){ // If --index You're going to fall into a dead circle
cur = cur->next;
}
return cur->val;
}
// Insert a node at the front of the linked list , After insertion , The newly inserted node is the new head node of the linked list
void addAtHead(int val) {
LinkedNode* newNode = new LinkedNode(val);
newNode->next = _dummyHead->next;
_dummyHead->next = newNode;
_size++;
}
// Add a node to the last side of the list
void addAtTail(int val) {
LinkedNode* newNode = new LinkedNode(val);
LinkedNode* cur = _dummyHead;
while(cur->next != nullptr){
cur = cur->next;
}
cur->next = newNode;
_size++;
}
// In the index Insert a new node before two nodes , for example index by 0, Then the newly inserted node is the new head node of the linked list .
// If index It's equal to the length of the list , The newly inserted node is the tail node of the linked list
// If index Greater than the length of the list , It returns null
void addAtIndex(int index, int val) {
if (index > _size) {
return;
}
LinkedNode* newNode = new LinkedNode(val);
LinkedNode* cur = _dummyHead;
while(index--) {
cur = cur->next;
}
newNode->next = cur->next;
cur->next = newNode;
_size++;
}
// Delete the first index Nodes , If index Greater than or equal to the length of the linked list , direct return, Be careful index It's from 0 At the beginning
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;
_size--;
}
// Print linked list
void printLinkedList() {
LinkedNode* cur = _dummyHead;
while (cur->next != nullptr) {
cout << cur->next->val << " ";
cur = cur->next;
}
cout << endl;
}
private:
int _size;
LinkedNode* _dummyHead;
};206 Reverse a linked list
Double finger needling : Definition cur The pointer points to the head node ,pre The pointer is initialized to null, Record tmp = cur->next and cur->next = pre, to update tmp and cur.
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;
} 24 Two or two exchange nodes in a linked list
ListNode* swapPairs(ListNode* head) {
ListNode* dummyhead = new ListNode(0);
dummyhead->next = head;
ListNode* cur = dummyhead;
while(cur->next != nullptr && cur->next->next != nullptr){
ListNode* tmp1 = cur->next;
ListNode* tmp2 = cur->next->next->next;
cur->next = cur->next->next;
cur->next->next = tmp1;
cur->next->next->next = tmp2;
cur = cur->next->next;
}
return dummyhead->next;
}19 Delete the last from the list n Nodes
ListNode* removeNthFromEnd(ListNode* head, int n) {
ListNode* dummyHead = new ListNode(0);
dummyHead->next = head;
ListNode* slow = dummyHead;
ListNode* fast = dummyHead;
//fast The pointer moves first n Step
while (n-- && fast->next != nullptr){
fast = fast->next;
}
// fast One more step ahead of time , Because we need to make slow Point to the previous node of the deleted node
fast = fast->next;
while(fast != nullptr){
fast = fast->next;
slow = slow->next;
}
slow->next = slow->next->next;
return dummyHead->next;
}142 Link list find ring
ListNode *detectCycle(ListNode *head) {
ListNode* fast = head;
ListNode* slow = head;
while(fast!= NULL && fast->next != NULL){
fast = fast->next->next;
slow = slow->next;
if(fast == slow){
ListNode* index1 = fast;
ListNode* index2 = head;
while(index1 != index2){
index1 = index1->next;
index2 = index2->next;
}
return index1;
}
}
return NULL;
}边栏推荐
- RISC-V架构下 FPU Context 的动态保存和恢复
- Linux MySQL installation
- YOLOX backbone——CSPDarknet的实现
- [e325: attention] VIM editing error
- 【bug】@JsonFormat 使用时出现日期少一天的问题
- MYCAT read / write separation and MySQL master-slave synchronization
- 软件系统依赖关系分析
- Applet cloud data, data request a method to collect data
- Pytoch read data set (two modes: typical data set and user-defined data set)
- 解决:jmeter5.5在win11下界面上的字特别小
猜你喜欢

【bug】@JsonFormat 使用时出现日期少一天的问题

Time Series Data Augmentation for Deep Learning: A Survey 之论文阅读

cookie加密 4 rpc方法确定cookie加密

Every (), map (), forearch () methods. There are objects in the array

4275. Dijkstra sequence

EasyExcel单sheet页与多sheet页写出
![[noi Simulation Competition] geiguo and time chicken (structure)](/img/4c/ed1b5bc2bed653c49b8b7922ce1674.png)
[noi Simulation Competition] geiguo and time chicken (structure)

零基础自学SQL课程 | 子查询

华为路由器:GRE技术
![[bug] @jsonformat has a problem that the date is less than one day when it is used](/img/09/516799972cd3c18795826199aabc9b.png)
[bug] @jsonformat has a problem that the date is less than one day when it is used
随机推荐
Redis实现全局唯一ID
"I can't understand Sudoku, so I choose to play Sudoku."
[noi Simulation Competition] geiguo and time chicken (structure)
听说你还在花钱从网上买 PPT 模板?
【ES6闯关】Promise堪比原生的自定义封装(万字)
支持向量机(SVC,NuSVC,LinearSVC)
Threejs glow channel 01 (unrealbroompass & layers)
Numpy NP in numpy c_ And np r_ Explain in detail
LeetCode之最长公共前缀
Project deployment related
[Niuke] convert string to integer
What do you mean by waiting for insurance records? Where should I go for filing?
华为路由器:GRE技术
Redis implements a globally unique ID
华为路由器:ipsec技术
[redis realize Secondary killing Business ①] Overview of Secondary killing Process | Basic Business Realization
Opencv maximum filtering (not limited to images)
Zero foundation self-study SQL course | sub query
P6117-[JOI 2019 Final]コイン集め【贪心】
Spark - LeftOuterJoin 结果条数与左表条数不一致