当前位置:网站首页>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;
}
};
边栏推荐
- JMeter connection database
- Blue Bridge Cup: the fourth preliminary - "simulated intelligent irrigation system"
- Unittest framework is basically used
- Use unique_ PTR forward declaration? [repetition] - forward declaration with unique_ ptr? [duplicate]
- Xctf attack and defense world crypto advanced area best_ rsa
- PR 2021 quick start tutorial, material import and management
- kubernetes集群搭建efk日志收集平台
- 2. Template syntax
- QT tutorial: signal and slot mechanism
- Global and Chinese market of charity software 2022-2028: Research Report on technology, participants, trends, market size and share
猜你喜欢
Chapter 1: drinking soft drinks, step tariff calculation, step tariff calculation function, personal income tax, solving square root inequality, simplifying solving square root inequality, solving dem
IPv6 experiment
Cesiumjs 2022 ^ source code interpretation [7] - Analysis of the request and loading process of 3dfiles
Today's work summary and plan: February 14, 2022
2022-06-25 网工进阶(十一)IS-IS-三大表(邻居表、路由表、链路状态数据库表)、LSP、CSNP、PSNP、LSP的同步过程
Geek Daily: the system of monitoring employees' turnover intention has been deeply convinced off the shelves; The meta universe app of wechat and QQ was actively removed from the shelves; IntelliJ pla
Phpstudy set LAN access
Use of aggregate functions
2022-06-30 advanced network engineering (XIV) routing strategy - matching tools [ACL, IP prefix list], policy tools [filter policy]
MPLS configuration
随机推荐
Parental delegation mechanism
Class loading process
2022-06-25 advanced network engineering (XI) IS-IS synchronization process of three tables (neighbor table, routing table, link state database table), LSP, cSNP, psnp, LSP
4. Data splitting of Flink real-time project
3. Data binding
第一章:拓广同码小数和s(d, n)
Leetcode 1189. Maximum number of balloons (special character count)
4. Data binding
[effective Objective-C] - block and grand central distribution
Sparse matrix (triple) creation, transpose, traversal, addition, subtraction, multiplication. C implementation
Commands related to files and directories
Professional interpretation | how to become an SQL developer
AcWing 1460. Where am i?
P5.js development - setting
Ae/pr/fcpx super visual effects plug-in package fxfactory
Realize user registration and login
Part 28 supplement (XXVIII) busyindicator (waiting for elements)
Nerfplusplus parameter format sorting
JMeter connection database
Chapitre 1: le roi de shehan a mal calculé