剑指Offer——反转链表
2024-08-29 12:11:32
Question
输入一个链表,反转链表后,输出链表的所有元素。
Solution
如果空间复杂度要求为O(1)的话,可以考虑用三个指针来进行反转
如果没有空间复杂度限制的话,可以考虑用一个栈,将节点全部push到栈用,然后再生成新的链表。
Code
/*
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};*/
class Solution {
public:
// 就地完成反转
ListNode* ReverseList(ListNode* pHead) {
ListNode* pre = NULL;
ListNode* head = pHead;
ListNode* next = head;
while (next) {
next = head->next;
head->next = pre;
pre = head;
if (next)
head = next;
}
return head;
}
// O(n)的空间
ListNode* ReverseList(ListNode* pHead) {
if (pHead == NULL)
return NULL;
stack<ListNode*> stack1;
ListNode* tmp = pHead;
while (tmp) {
stack1.push(tmp);
tmp = tmp->next;
}
ListNode* first = new ListNode(-1);
pHead = first;
while (!stack1.empty()) {
ListNode* current = stack1.top();
stack1.pop();
first->next = current;
first = current;
}
first->next = NULL;
return pHead->next;
}
};
最新文章
- 商品条形码(JBarcode)
- 一次外企QQ面试
- 分享一个递归无限级拼接Json的方法---ExtJs的TreePanel和TreeGrid均适用(Ef,Lambda,Linq,IQueryable,List)
- Resharper快捷键
- [转]Oracle中使用Rownum分页详细例子
- jpg Test
- C++ find 函数用法
- NOIP 2013 货车运输【Kruskal + 树链剖分 + 线段树 】【倍增】
- 【找规律】CodeForce #258 Problem A——Game With Sticks
- 第一章. ActionScript 语言基础
- 解决没有X11/Xlib.h 的错误
- 决策树之ID3,C4.5及CART
- MySQL之优化
- 牛客网-小白月赛6-J-洋灰三角
- mysql三级连查,左连
- what&#39;s the difference between grouping and facet in lucene 3.5
- electron安装到第一个实例
- ubuntu12.04下Qt调试器的使用
- Nginx 用log_format设置日志格式
- Jenkins 集成Unity3D Xcode