cpp-algo-cases/utils/list_node.hpp

60 lines
1.5 KiB
C++
Raw Permalink Normal View History

2024-02-21 09:31:34 +08:00
/**
* File: list_node.hpp
* Created Time: 2021-12-19
* Author: krahets (krahets@163.com)
*/
#pragma once
#include <iostream>
#include <vector>
using namespace std;
/* Definition for a singly-linked list node */
struct ListNode
{
int val; // <20><><EFBFBD><EFBFBD><EFBFBD>ǽڵ<C7BD><DAB5><EFBFBD>ֵ
ListNode *next; // <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ָ<EFBFBD><D6B8><EFBFBD><EFBFBD>һ<EFBFBD><D2BB><EFBFBD>ڵ<EFBFBD><DAB5><EFBFBD>ָ<EFBFBD><D6B8>
ListNode(int x) : val(x), next(nullptr)
{ // <20><><EFBFBD><EFBFBD><ECBAAF>: <20><>ʼ<EFBFBD><CABC><EFBFBD>ڵ<EFBFBD><DAB5><EFBFBD>ֵΪx, ָ<><D6B8><EFBFBD><EFBFBD>һ<EFBFBD><D2BB><EFBFBD>ڵ<EFBFBD><DAB5><EFBFBD>ָ<EFBFBD><D6B8>Ϊ<EFBFBD><CEAA>
}
};
/* Generate a linked list with a vector */ // <20><>һ<EFBFBD><D2BB>vector<6F><72><EFBFBD><EFBFBD>һ<EFBFBD><D2BB><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
ListNode *vecToLinkedList(vector<int> list)
{
ListNode *dum = new ListNode(0); // <20><><EFBFBD><EFBFBD>һ<EFBFBD><D2BB><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ڵ<EFBFBD> dum (ֵΪ0)
ListNode *head = dum; // <20><><EFBFBD><EFBFBD>һ<EFBFBD><D2BB>ָ<EFBFBD><D6B8><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ڵ<EFBFBD><DAB5><EFBFBD>ָ<EFBFBD><D6B8> head
for (int val : list)
{
head->next = new ListNode(val); // <20><><EFBFBD><EFBFBD>һ<EFBFBD><D2BB><EFBFBD>½ڵ<C2BD>, ֵΪval, <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ָ<EFBFBD><EFBFBD><EBB8B3>head->next
head = head->next; // headָ<64><D6B8><EFBFBD><EFBFBD>һ<EFBFBD><D2BB><EFBFBD>ڵ<EFBFBD>
}
return dum->next; // <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ͷ<EFBFBD>ڵ<EFBFBD>
}
/* Get a list node with specific value from a linked list */
ListNode *getListNode(ListNode *head, int val)
{
// <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>, <20>ҵ<EFBFBD>ֵΪval<61>Ľڵ<C4BD>
while (head != nullptr && head->val != val)
{
head = head->next; // ָ<><D6B8><EFBFBD><EFBFBD>һ<EFBFBD><D2BB><EFBFBD>ڵ<EFBFBD>
}
return head; // <20><><EFBFBD><EFBFBD><EFBFBD>ҵ<EFBFBD><D2B5>Ľڵ<C4BD>, <20><><EFBFBD><EFBFBD>û<EFBFBD><C3BB><EFBFBD>ҵ<EFBFBD>, <20><><EFBFBD><EFBFBD>nullptr
}
/* Free the memory allocated to a linked list */
void freeMemoryLinkedList(ListNode *cur)
{
// <20>ͷ<EFBFBD><CDB7>ڴ<EFBFBD>
ListNode *pre;
while (cur != nullptr) // <20><>ǰ<EFBFBD>ڵ㲻Ϊ<E3B2BB><CEAA>
{
pre = cur; // preָ<65><D6B8><EFBFBD><EFBFBD>ǰ<EFBFBD>ڵ<EFBFBD>
cur = cur->next; // <20><>ǰ<EFBFBD>ڵ<EFBFBD>ָ<EFBFBD><D6B8><EFBFBD><EFBFBD>һ<EFBFBD><D2BB><EFBFBD>ڵ<EFBFBD>
delete pre; // <20>ͷ<EFBFBD>preָ<65><D6B8><EFBFBD>Ľڵ<C4BD>
}
}