剑指offer 14 反转链表
2016-03-29 16:36
483 查看
题目描述
输入一个链表,反转链表后,输出链表的所有元素。思路
运用递归将首尾链表的值相交换。
由于java中的函数参数传递,对于普通类型,只是值传递,而对于自定义类,则是引用传递。
/* public class ListNode { int val; ListNode next = null; ListNode(int val) { this.val = val; } }*/ public class Solution { public ListNode temp; public int mark=0; public void find_ListNode(ListNode head){ if(head.next!=null)find_ListNode(head.next); if(mark==1)return ; int number_temp=temp.val; temp.val=head.val; head.val=number_temp; if(temp==head||(temp.next==head)){mark=1;return ;}//如果两个指针都完全遍历一遍的话,那么元素的值是不会变的,如果遍历过程中相遇到,那么就结束掉。 if(temp.next!=null)temp=temp.next; } public ListNode ReverseList(ListNode head) { if(head==null)return null; temp=head; ListNode test; test=head; find_ListNode(test); return head; } }
第二个代码则是将链表的next指针反转,第一个的代码是讲listnode中的值(val)反转而已。
/* public class ListNode { int val; ListNode next = null; ListNode(int val) { this.val = val; } }*/ public class Solution { public ListNode ReverseList(ListNode head) { ListNode pre=null; ListNode next=null; while(head!=null){ next=head.next; head.next=pre; pre=head; head=next; } return pre; } }
相关文章推荐
- js一对多,添加属性
- Caffe学习笔记
- CSS:IE,Chrome,Firefox兼容性和CSS Hack(转载)
- js获取文件大小
- 再见,RichFaces
- mysql_fetch_row
- js判断为空
- 使用Bootstrap框架
- CloseableReference: Finalized without closing
- js继承
- 个人常用的css属性
- 多种方法实现H5网页图片动画效果;
- Libevent源码分析(五)--- evbuffer的基本操作
- 基于javascript实现简单的抽奖系统
- 11款最轻量级的CSS框架
- js获取某个div下的input
- js实现继承的几种方式
- jQuery.Validate验证库
- ReactiveCocoa
- div+css常用属性参数