206. Reverse Linked List
2016-02-10 23:46
323 查看
用递归或者栈
递归
public class Solution {
public ListNode reverseList(ListNode head) {
if(head==null || head.next==null)
return head;
ListNode nextNode=head.next;
ListNode newHead=reverseList(nextNode);
nextNode.next=head;
//head.next=null;
return newHead;
}
}
栈
public class Solution {
public ListNode reverseList(ListNode head) {
if(head==null)
return null;
Stack<ListNode> stack =new Stack<ListNode>();
ListNode temp=head;
while(temp!=null){
stack.push(temp);
temp=temp.next;
}
head=stack.pop();
temp=head;
while(!stack.isEmpty()){
temp.next=stack.pop();
temp=temp.next;
}
temp.next=null;
return head;
}
}
递归
public class Solution {
public ListNode reverseList(ListNode head) {
if(head==null || head.next==null)
return head;
ListNode nextNode=head.next;
ListNode newHead=reverseList(nextNode);
nextNode.next=head;
//head.next=null;
return newHead;
}
}
栈
public class Solution {
public ListNode reverseList(ListNode head) {
if(head==null)
return null;
Stack<ListNode> stack =new Stack<ListNode>();
ListNode temp=head;
while(temp!=null){
stack.push(temp);
temp=temp.next;
}
head=stack.pop();
temp=head;
while(!stack.isEmpty()){
temp.next=stack.pop();
temp=temp.next;
}
temp.next=null;
return head;
}
}
相关文章推荐
- jQuery的Ajax应用
- 2016-2-10 linux基础学习12
- 理解js闭包(二)
- POJ 2516Minimum Cost(最小费用最大流)
- 前端试题-什么是css sprite?优缺点?
- Android开发学习之路--UI之ListView
- ListView 使用 ViewHolder
- Block的详细使用和面试注意点
- BaseAdapter中重写getview的心得以及发现convertView回收的机制
- View的setTag和getTag方法
- 阅读整理《从0到1》
- android 获取屏幕高度和宽度 的方法
- 360昆仑万维12亿美元收购Opera
- 数据结构之哈希表
- 关于OF和CF
- 手势操作知识大餐 ——iOS
- poj_3974 Palindrome(最长回文子串)
- 如何节省网站流量
- 学习记录 - 3
- POJ 2195 Going Home(费用流)