实现单向链表的反转
2016-09-29 10:29
381 查看
1.可以用临时变量前移方式逐步实现反转。
利用前中后三个临时变量,逐步前移并反转实现
public static <T> ListNode<T> reverseListTest2(ListNode<T> node){
if (node.next!=null){
reverseListTest2(node.next).next=node;
node.next=null;
return node;
}
return node;
}
说明:
1> 节点声明
class ListNode<T>{
T value;
ListNode<T> next;
public ListNode() {
this(null);
}
public ListNode(T value) {
this(value,null);
}
public ListNode(T value,ListNode<T> next) {
this.value=value;
this.next=next;
}
@Override
public String toString() {
return ""+value;
}
}
2>数据测试
public static void main(String[] args) {
//创建单向链表,从0到10
ListNode<Integer> start=new ListNode<Integer>(10);
ListNode<Integer> end=start;
for (int i = 9; i >=0;--i) {
ListNode<Integer> node=new ListNode<Integer>(i,start);
start=node;
}
//反转单向链表,得到新根
ListNode<Integer> newRoot=reverseListTest1(start);
while(newRoot!=null){
System.out.printf(newRoot+" ");
newRoot=newRoot.next;
}
System.out.println();
//再次反转,反转前根为end,反转后根为start
reverseListTest2(end);
while(start!=null){
System.out.print(start+" ");
start=start.next;
}
}
3>测试输出
10 9 8 7 6 5 4 3 2 1 0
0 1 2 3 4 5 6 7 8 9 10
利用前中后三个临时变量,逐步前移并反转实现
public static <T> ListNode<T> reverseListTest1(ListNode<T> node){ ListNode<T> pre=null; ListNode<T> cur=node; ListNode<T> next=cur.next; while(next!=null){ pre=cur; cur=next; next=next.next; cur.next=pre; } node.next=null; return cur; }2.可以利用递归的形式逐步逐步回调并反转
public static <T> ListNode<T> reverseListTest2(ListNode<T> node){
if (node.next!=null){
reverseListTest2(node.next).next=node;
node.next=null;
return node;
}
return node;
}
说明:
1> 节点声明
class ListNode<T>{
T value;
ListNode<T> next;
public ListNode() {
this(null);
}
public ListNode(T value) {
this(value,null);
}
public ListNode(T value,ListNode<T> next) {
this.value=value;
this.next=next;
}
@Override
public String toString() {
return ""+value;
}
}
2>数据测试
public static void main(String[] args) {
//创建单向链表,从0到10
ListNode<Integer> start=new ListNode<Integer>(10);
ListNode<Integer> end=start;
for (int i = 9; i >=0;--i) {
ListNode<Integer> node=new ListNode<Integer>(i,start);
start=node;
}
//反转单向链表,得到新根
ListNode<Integer> newRoot=reverseListTest1(start);
while(newRoot!=null){
System.out.printf(newRoot+" ");
newRoot=newRoot.next;
}
System.out.println();
//再次反转,反转前根为end,反转后根为start
reverseListTest2(end);
while(start!=null){
System.out.print(start+" ");
start=start.next;
}
}
3>测试输出
10 9 8 7 6 5 4 3 2 1 0
0 1 2 3 4 5 6 7 8 9 10
相关文章推荐
- C递归实现单向链表的反转
- C递归实现单向链表的反转
- C递归实现单向链表的反转
- Java实现单向链表反转
- JAVA实现单向链表反转2
- java实现单向链表CRUD,反转,排序,查找倒数第k个元素,递归输出等操作
- C语言实现单向链表的反转
- C递归实现单向链表的反转
- 反转单向链表的实现
- 用C++类实现单向链表的增删查和反转操作方法
- Java实现单向链表反转
- python实现反转部分单向链表
- 反转单向链表 (java 语言实现)
- 单向链表遍历反转 Javascript实现
- c++实现单向链表反转的学习总结
- 单向链表实现反转
- C递归实现单向链表的反转
- 16.单向链表的一些基本操作实现(链表反转,链表有环无环判断,链表冒泡排序,链表快速排序)
- 转贴-- 单向链表的实现 C# http://blog.csdn.net/a497785609/archive/2009/09/29/4617692.aspx
- java 单向链表的实现