实现单向链表的反转

1.可以用临时变量前移方式逐步实现反转。

利用前中后三个临时变量,逐步前移并反转实现

	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 






  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值