Leetcode Reverse Linked List
2015-09-11 01:01
281 查看
Reverse a singly linked list.
Hint:
A linked list can be reversed either iteratively or recursively. Could you implement both?
Java Code:
Iteratively:
Recursively:
版本一:
版本二:
Reference:
1. http://www.programcreek.com/2014/05/leetcode-reverse-linked-list-java/
2. https://leetcode.com/discuss/34474/in-place-iterative-and-recursive-java-solution
Hint:
A linked list can be reversed either iteratively or recursively. Could you implement both?
Java Code:
Iteratively:
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */ public class Solution { public ListNode reverseList(ListNode head) { if(head == null || head.next == null) { return head; } ListNode p1 = head; ListNode p2 = head.next; head.next = null; while(p1 != null && p2 != null) { ListNode p3 = p2.next; p2.next = p1; p1 = p2; if(p3!= null) { p2 = p3; }else { break; } } return p2; } }
Recursively:
版本一:
public ListNode reverseList(ListNode head) { if(head==null || head.next == null) return head; //get second node ListNode second = head.next; //set first's next to be null head.next = null; ListNode rest = reverseList(second); second.next = head; return rest; }
版本二:
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); }
Reference:
1. http://www.programcreek.com/2014/05/leetcode-reverse-linked-list-java/
2. https://leetcode.com/discuss/34474/in-place-iterative-and-recursive-java-solution
相关文章推荐
- 1094. The Largest Generation (25)
- P2P之UDP穿透NAT的原理与实现
- 移动客户端开发的一点小小的思考
- atlas tutorial
- 剑指Offer面试题:27.最小的k个数
- MySQL for mac如何调出命令行客户端MySQL Command Line Client
- CentOS6.5下kafka+ZooKeeper下载与安装详细教程-多机版本2-附录
- 基于jqery插件 实现粘贴板
- CentOS6.5下kafka+ZooKeeper下载与安装详细教程-多机版本2
- 蓝懿iOS培训日志8 控件学习2
- epoll模型中LT、ET模式分析
- 计算DOM节点
- RSA加密算法
- html定位
- LeetCode "Find the Celebrity"
- 操作偶数、奇数、指定下标的元素
- myecplise中导入项目出现红色感叹号的问题,项目运行不正常
- 来到惠普的第一篇博文
- GMT5.1.2_基础_Windows下安装GMT过程
- 总结一下最近用到的技术(2)--JsonSchema和JsonSchemaValidator