当前位置:网站首页>Print linked list from end to end
Print linked list from end to end
2022-07-03 20:00:00 【stitchshaw】
List of articles
The original title is :
https://www.nowcoder.com/practice/d0267f7f55b3412ba93bd35cfa8e8035?tpId=13&tqId=23278&ru=/practice/75e878df47f24fdc9dc3e400ec6058ca&qru=/ta/coding-interviews/question-ranking
1. Call library function reverse Realization vector Flip of internal elements .
Time :o(n) Space :o(n)
/** * struct ListNode { * int val; * struct ListNode *next; * ListNode(int x) : * val(x), next(NULL) { * } * }; */
class Solution {
public:
vector<int> printListFromTailToHead(ListNode* head) {
vector<int> A;
while(head){
// while(head!=NULL) while(head!=nullptr) Can also be .
A.push_back(head->val);
head = head->next;
}
reverse(A.begin(), A.end()); // Directly call library functions to realize vector Flip of internal elements .
return A;
}
};
2. Recursive method
Time :o(n) Space :o(n)
But this method will cause stack overflow ( Too many recursive call layers ). That is, when the linked list is very long, it may cause function call stack overflow .
/** * struct ListNode { * int val; * struct ListNode *next; * ListNode(int x) : * val(x), next(NULL) { * } * }; */
class Solution {
public:
vector<int> ans;
vector<int> printListFromTailToHead(ListNode* head) {
if(!head) return ans; // if(head == nullptr) or if(head == NULL)
printListFromTailToHead(head->next);
ans.push_back(head->val);
return ans;
}
};
3. Stack method
Time :o(n) Space :o(n)
/** * struct ListNode { * int val; * struct ListNode *next; * ListNode(int x) : * val(x), next(NULL) { * } * }; */
class Solution {
public:
vector<int> printListFromTailToHead(ListNode* head) {
vector<int> res;
stack<int> nodes;
ListNode* node = head;
// Push
while(node != nullptr){
// or head != NULL or while(head)
nodes.push(node->val);
node = node->next;
}
// Out of the stack And store the outbound node in res
while(!nodes.empty()){
res.push_back(nodes.top());
nodes.pop();
}
return res;
}
};
To simplify the :
class Solution {
public:
vector<int> printListFromTailToHead(ListNode* head) {
vector<int> res;
stack<int> nodes;
// Push
while(head != nullptr){
// or head != NULL or while(head)
nodes.push(head->val);
head = head->next;
}
// Out of the stack And store the outbound node in res
while(!nodes.empty()){
res.push_back(nodes.top());
nodes.pop();
}
return res;
}
};
4. Reverse a linked list ( Change the list structure )
Time complexity :O(n), Traverse the list once
Spatial complexity :O(1)
class Solution {
public:
vector<int> printListFromTailToHead(ListNode* head) {
ListNode *pre = nullptr;
ListNode *cur = head;
ListNode *nex = head; // ListNode *nex = nullptr; also ok.
// By moving 3 Pointer reverse linked list ( Generated a new linked list , It is the reverse linked list of the original linked list )
while(cur){
// The cycle condition is The current node of the original linked list is not a null pointer
// First step : Save the next node of the current node
nex = cur->next;
// The second step : Make the current node of the original linked list next The pointer points to the last node of the inverted linked list ( Namely pre Pointed node , remember pre Initially null pointer ),
// It also means cutting off the connection between the current node of the original linked list and its next node .
cur->next = pre;
// The third step :( Make ) Reverse the last node of the linked list, that is, the current node of the original linked list .
pre = cur;
// Step four :( Make ) The current node of the original linked list points to the next node of the original linked list . thus , The end of a cycle . repeat .
cur = nex;
}
// while At the end of the cycle ,cur Of course nullptr,pre Point to the head node of the inverted linked list .
vector<int> res;
while(pre){
res.push_back(pre->val);
pre = pre->next;
}
return res;
}
};
5. utilize vector Of insert characteristic
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */
class Solution {
public:
vector<int> reversePrint(ListNode* head) {
vector<int> res;
ListNode* pre=head;
while(pre){
res.insert(res.begin(),pre->val);
pre=pre->next;
}
return res;
}
};
/** * struct ListNode { * int val; * struct ListNode *next; * ListNode(int x) : * val(x), next(NULL) { * } * }; */
class Solution {
public:
vector<int> printListFromTailToHead(ListNode* head) {
vector<int> res;
if(!head) return res;
while(head){
// Insert each round in the head
res.insert(res.begin(), head->val);
head = head->next;
}
return res;
}
};
边栏推荐
- Strict data sheet of new features of SQLite 3.37.0
- Upgrade PIP and install Libraries
- CesiumJS 2022^ 源码解读[7] - 3DTiles 的请求、加载处理流程解析
- 2022-06-28 网工进阶(十三)IS-IS-路由过滤、路由汇总、认证、影响ISIS邻居关系建立的因素、其他命令和特性
- Microservice knowledge sorting - search technology and automatic deployment technology
- Pat grade B 1009 is ironic (20 points)
- 2022-07-02 网工进阶(十五)路由策略-Route-Policy特性、策略路由(Policy-Based Routing)、MQC(模块化QoS命令行)
- Ae/pr/fcpx super visual effects plug-in package fxfactory
- Chapter 1: find all factorial sums, Grand Prix site unified programming, three factorial sums, graphic point scanning, recursive factorial n of n!, Find the factorial n of n!, King Shehan miscalculate
- 2022 - 06 - 30 networker Advanced (XIV) Routing Policy Matching Tool [ACL, IP prefix list] and policy tool [Filter Policy]
猜你喜欢
Cesiumjs 2022 ^ source code interpretation [7] - Analysis of the request and loading process of 3dfiles
How to read the source code [debug and observe the source code]
2022-06-25 网工进阶(十一)IS-IS-三大表(邻居表、路由表、链路状态数据库表)、LSP、CSNP、PSNP、LSP的同步过程
Acquisition and transmission of parameters in automatic testing of JMeter interface
第一章:求同吗小数和s(d, n)
IPv6 experiment
kubernetes集群搭建efk日志收集平台
Kubernetes cluster builds efk log collection platform
FPGA learning notes: vivado 2019.1 project creation
BOC protected alanine porphyrin compound TAPP ala BOC BOC BOC protected phenylalanine porphyrin compound TAPP Phe BOC Qi Yue supply
随机推荐
Global and Chinese market of full authority digital engine control (FADEC) 2022-2028: Research Report on technology, participants, trends, market size and share
BOC protected amino acid porphyrins TAPP ala BOC, TAPP Phe BOC, TAPP Trp BOC, Zn · TAPP ala BOC, Zn · TAPP Phe BOC, Zn · TAPP Trp BOC Qiyue
Explore the internal mechanism of modern browsers (I) (original translation)
Sparse matrix (triple) creation, transpose, traversal, addition, subtraction, multiplication. C implementation
Derivation of decision tree theory
Difference between surface go1 and surface GO2 (non professional comparison)
NFT without IPFs and completely on the chain?
Vscode reports an error according to the go plug-in go get connectex: a connection attempt failed because the connected party did not pro
Chapter 1: simplify the same code decimal sum s (D, n)
3. Data binding
2022-06-30 advanced network engineering (XIV) routing strategy - matching tools [ACL, IP prefix list], policy tools [filter policy]
2022-06-27 advanced network engineering (XII) IS-IS overhead type, overhead calculation, LSP processing mechanism, route revocation, route penetration
[effective Objective-C] - block and grand central distribution
Part 28 supplement (XXVIII) busyindicator (waiting for elements)
How to read the source code [debug and observe the source code]
Gym welcomes the first complete environmental document, which makes it easier to get started with intensive learning!
Global and Chinese markets of cast iron diaphragm valves 2022-2028: Research Report on technology, participants, trends, market size and share
第一章: 舍罕王失算
Native table - scroll - merge function
Chapter 2: 4-digit Kaplan number, search even digit Kaplan number, search n-digit 2-segment sum square number, m-digit ingenious square number without 0, specify the number to form a 7-digit square nu