leetcode day7
2015-11-28 22:38
302 查看
这道题弄的心好累。。
【Reverse Linked List】206
描述:
Reverse a singly linked list.
click to show more hints.
Hint:
A linked list can be reversed either iteratively or recursively. Could you implement both?
思路:
增加一个全局节点newHead,用来指向新的头部,用[b]用一个临时节点next来遍历整个链表,用来当旧的头部head,例如链表1-2-3-4,第一遍循环,newhead指向1,指向null,head是2,指向剩余的链表,2-3-4,然后第二遍循环,newhead指向2-1,head指向剩余的链表,3-4。。。以此类推,直到循环结束。[/b]
还有递归的算法:
【Reverse Linked List】206
描述:
Reverse a singly linked list.
click to show more hints.
Hint:
A linked list can be reversed either iteratively or recursively. Could you implement both?
思路:
增加一个全局节点newHead,用来指向新的头部,用[b]用一个临时节点next来遍历整个链表,用来当旧的头部head,例如链表1-2-3-4,第一遍循环,newhead指向1,指向null,head是2,指向剩余的链表,2-3-4,然后第二遍循环,newhead指向2-1,head指向剩余的链表,3-4。。。以此类推,直到循环结束。[/b]
// iterative solution public ListNode reverseList(ListNode head) { ListNode newHead = null; while(head != null){ ListNode next = head.next; head.next = newHead; newHead = head; head = next; } return newHead; }
还有递归的算法:
// recursive solution public ListNode reverseList(ListNode head) { return reverseListInt(head, null); } public ListNode reverseListInt(ListNode head, ListNode newHead) { if(head == null) return newHead; ListNode next = head.next; head.next = newHead; return reverseListInt(next, head); }
相关文章推荐
- 一行代码解决各种IE兼容问题,IE6,IE7,IE8,IE9,IE10 http://www.jb51.net/css/383986.html
- 让你轻松进阶高手的十大算法
- iOS Core data多线程并发访问的问题
- com.microsoft.sqlserver.jdbc.SQLServerException: 对象名 ‘xxx' 无效
- 信息安全系统设计基础 实验三 实时系统的移植 20135327郭皓 20135329 李海空
- 工作一周+文章预备
- 成功的背后!(给所有的IT人)
- mysql limit分页查询优化写法
- Java对日期的处理
- logback logback.xml常用配置详解(三) <filter>
- php数据库操作封装类
- java连接oracle数据库的实现代码
- masonry 轻量级自动布局
- hdu5587 BestCoder Round #64 (div.2)
- bzoj2330 糖果 差分约束
- hdu5587 BestCoder Round #64 (div.2)
- el和ognl取pageContext、parameters、request、session、application 等处的属性值
- iOS网络监控— BMReachability
- url-pattern
- HDU 1710