剑指Offer:反转链表
来源:互联网 发布:2017理财软件排行 编辑:程序博客网 时间:2024/04/30 12:59
方法一:
简单粗暴,还有点小问题。只是改了节点的值,没有真正交换2个节点
/*public class ListNode { int val; ListNode next = null; ListNode(int val) { this.val = val; }}*/public class Solution { public ListNode ReverseList(ListNode head) {int len = getLength(head); ListNode a = head; ListNode b = null; int n = 0; for(int i=1,j=len-1;i<j;i++,j--){ b = getByIndex(head,j); n = b.val; b.val = a.val; a.val = n; a = a.next; } return head; } public int getLength(ListNode head) { if( head == null ) return 0; ListNode a = head; int len = 1 ; while(a != null){a = a.next; len++; } return len; } public ListNode getByIndex(ListNode head, int x){ if( x <= 0 || head ==null) return null; ListNode a = head; int length =1; while(a != null) { if( x == length ){ return a; } a = a.next; length++; } return null; }}方法2
看了一些别人的代码后发现了这种方法,觉得确实很好。就实现了一遍。
public class Solution { public ListNode ReverseList(ListNode head) { if(head == null) return null; ListNode next = null; ListNode pre = null; while(head != null) { next = head.next; head.next = pre; pre = head; head = next; } return pre; }}
0 0
- 剑指offer:反转链表
- 剑指offer--反转链表
- 剑指offer--反转链表
- 剑指Offer-反转链表
- 《剑指offer》反转链表
- 剑指 offer:反转链表
- 剑指offer-反转链表
- 剑指offer 反转链表
- 剑指offer-反转链表
- 剑指offer:反转链表
- [剑指offer]反转链表
- 《剑指offer》-反转链表
- 剑指Offer:反转链表
- 剑指offer----反转链表
- 剑指offer|反转链表
- 《剑指offer》反转链表
- 【剑指offer】反转链表
- 剑指offer-反转链表
- 关于有偿提供拼图响应式后台的通知
- iOS7 tabbar 阴影线问题
- Android性能优化之数据库优化
- Android AccessibilityDelegate的使用
- iptables防火墙原理
- 剑指Offer:反转链表
- Android Universal Image Loader 源码分析
- HDOJ 5391 Zball in Tina Town
- Android4.4 home键禁用
- hdoj-1273-漫步森林
- Gridview控件整体的高度设置
- 通过考试申报中级职称办理上海居住证积分加分和居转户
- 关键字static/const的作用
- EventBus 源码解析