Leetcode 206
来源:互联网 发布:怎么办淘宝 编辑:程序博客网 时间:2024/04/20 06:43
Total Accepted: 86124 Total Submissions: 225095 Difficulty: Easy
Reverse a singly linked list.
第一个想到的是栈,把每个节点依次存入,在出栈变可直接获得答案 ;
代码如下 :
class Solution {public: ListNode* reverseList(ListNode* head) { stack<ListNode*>stk ; if ( head == NULL ) return NULL ; while (head){ stk.push(head) ; head = head -> next ; } ListNode *p , *q , *resHead ; p = resHead = stk.top() ; stk.pop() ; while (stk.size() > 0 ) { q = stk.top() ; if (p == resHead) { p = resHead ->next = q ; stk.pop() ; } else { p -> next = q ; p = q ; stk.pop() ; } } p -> next = NULL ; return resHead ; }}; // 容易理解,但是代码太长 ;
后来想到另外一种方法 。直接把新的头结点移动就行了 ,诶。
<pre name="code" class="cpp">class Solution {public: ListNode* reverseList(ListNode* head) { if ( head == NULL ) return NULL ; ListNode *pre=NULL , *q=head , *tmp=NULL; while (q){ tmp = q->next; // 要保存下一个节点,不然整个链表就断了 ; q -> next = pre ; pre = q ; q = tmp ; } return pre ; }};
0 0
- Leetcode 206
- LEETCODE 206
- Leetcode 206
- leetcode 206
- LeetCode #206
- leetcode 237和leetcode 206
- <LeetCode><Easy>206 ReverseLinkedList
- LeetCode 206 单链表逆置
- leetcode
- [leetcode]
- LeetCode
- leetcode
- leetcode
- leetcode:
- leetcode:
- LeetCode
- leetcode
- LEETCODE
- 校园网&openwrt记(一)接触openwrt的原因
- JavaWeb学习总结(二)——Tomcat服务器学习和使用(一)
- 谷歌电子市场笔记4
- V8 JavaScript引擎Windows+VS2015编译遇到错误解决经验
- 微信红包的架构设计简介
- Leetcode 206
- 个人管理 - 我是这样偷着做架构的
- HDU 3468Treasure Hunting
- 数据库连接池、静态连接,普通连接的比较2(多线程)
- 自定义的密码输入判断
- Linux apache单独编译mod_rewrite.so
- 44.View the Exhibit and examine the structure of the ORD table.
- 用OC编写的各种排序算法
- spring中的注解