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;
}
};

最新文章

  1. 商品条形码(JBarcode)
  2. 一次外企QQ面试
  3. 分享一个递归无限级拼接Json的方法---ExtJs的TreePanel和TreeGrid均适用(Ef,Lambda,Linq,IQueryable,List)
  4. Resharper快捷键
  5. [转]Oracle中使用Rownum分页详细例子
  6. jpg Test
  7. C++ find 函数用法
  8. NOIP 2013 货车运输【Kruskal + 树链剖分 + 线段树 】【倍增】
  9. 【找规律】CodeForce #258 Problem A——Game With Sticks
  10. 第一章. ActionScript 语言基础
  11. 解决没有X11/Xlib.h 的错误
  12. 决策树之ID3,C4.5及CART
  13. MySQL之优化
  14. 牛客网-小白月赛6-J-洋灰三角
  15. mysql三级连查,左连
  16. what&#39;s the difference between grouping and facet in lucene 3.5
  17. electron安装到第一个实例
  18. ubuntu12.04下Qt调试器的使用
  19. Nginx 用log_format设置日志格式
  20. Jenkins 集成Unity3D Xcode

热门文章

  1. 深入了解UIAutomation 的API
  2. 48、ViewFlow ---- 滑动广告页
  3. Retrofit学习笔记(一)
  4. 关于java后台如何接收xml格式的数据
  5. hdu1174(3维射线与圆是否相交)
  6. Win7系统安装 MySQL 8.0.11
  7. Python菜鸟之路:DOM基础
  8. velocity 遍历EventHandler Iterator
  9. python函数回顾:all()
  10. Python多进程multiprocessing