【Leetcode】Reversed Linked List
来源:互联网 发布:手机刷软件 编辑:程序博客网 时间:2024/06/04 23:19
【题目】
Reverse a singly linked list.
Hint:
A linked list can be reversed either iteratively or recursively. Could you implement both?
【思路】
我自己想的办法就是可以用一个stack,先把每一个元素都装进去,然后在倒着吐出来。
放在新的list里面。
需要两个指针,一个指向新的list的root,另一个走一遍新list.
【代码】自己提交的代码,一遍过
/** * 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) return null; Stack<Integer> stack = new Stack<Integer>(); while(head!=null){ stack.push(head.val); head = head.next; } System.out.println(stack); ListNode newRoot = new ListNode(0); ListNode p = new ListNode(stack.pop()); newRoot.next = p; while(!stack.isEmpty()){ p.next = new ListNode(stack.pop()); p = p.next; } return newRoot.next; }}
[Other’s code]
Iterative ! !
public class Solution { public ListNode reverseList(ListNode head) { if(head == null) return head; ListNode next = head.next; head.next = null; while(next != null){ ListNode temp = next.next; next.next = head; head = next; next = temp; } return head; }}Recursive!!!!public class Solution { public ListNode reverseList(ListNode head) { if(head == null) return head; ListNode next = head.next; head.next = null; return recursive(head,next); } private ListNode recursive(ListNode head, ListNode next){ if(next == null) return head; ListNode temp = next.next; next.next = head; return recursive(next,temp); }}
0 0
- 【Leetcode】Reversed Linked List
- 【LeetCode】Linked List Cycle
- Leetcode: Linked List Cycle
- Leetcode Linked List Cycle
- Leetcode: Linked List Cycle
- LeetCode:Linked List Cycle
- [LeetCode]Linked List Cycle
- LeetCode | Linked List Cycle
- Leetcode: Linked List Cycle
- LeetCode: Linked List Cycle
- LeetCode - Linked List Cycle
- [LeetCode] - Linked List Cycle
- LeetCode - Linked List Cycle
- [LeetCode]Linked List Cycle
- 【LeetCode】Linked List Cycle
- Linked List Cycle - LeetCode
- 【LeetCode】Linked List Cycle
- Linked List Cycle -- LeetCode
- 换网站Logo图片---轻开电子商务系统(企业入门级B2C网站)
- hdu2005 关于输入的技巧及初始化问题
- mysql触发器讲解
- Webservice(基础)——DTD
- 内存和FLASH的区别
- 【Leetcode】Reversed Linked List
- 查找二叉树的操作
- 黑马程序员——Java中类的加载与反射笔记
- flex+bison解析配置文件
- 手机APP UI设计尺寸基础知识
- 1012--映射一对多关联关系(.双向 1-n)
- 存储过程与事务
- android 中 图形缩放
- nyoj216