2.3 反转链表(线性表-链表)——【LeetCode】

在这里插入图片描述

package com.lianbiao.java;

import org.junit.Test;

class three {

	public static void main(String[] args) {
		ListNode node1 = new ListNode(1);
		ListNode node2 = new ListNode(2);
		ListNode node3 = new ListNode(3);
		ListNode head = node1;
		node1.next = node2;
		node2.next = node3;
				
		
		ListNode last = reverseList2(head);
		
		while(last != null) {
			System.out.println(last);
			last = last.next;
		}
	}

//	
	//双指针法
	public ListNode reverseList(ListNode head) {

		ListNode prev = null;
		ListNode cur = head;//cur和prev主要用来完成改变指针方向
		ListNode temp = null;//temp作为辅助,保存变量
		
		while(cur != null) {
			temp = cur.next;//保存下一个结点
			cur.next = prev; // 改变指针方向
			
			prev = cur;//prev向前移动
			cur = temp;// cur向前移动,可以想象到,prev先向前移动到cur,cur再移动到cur.next
		}
		return prev;//此时cur为null 退出循环,prev = 最后一个元素		
	}
	
	//递归
	public ListNode reverseList1(ListNode head) {
		return reverse(null, head);
	}

	private ListNode reverse(ListNode prev, ListNode cur) {
		if(cur == null) {
			return prev;
		}
		ListNode temp = null;
		temp = cur.next;//保存下一个结点
		cur.next = prev;//反转
		//更新prev、cur位置;
		//prev = cur;
		//cur = temp;
		return reverse(cur, temp);
	}
//	
	
	//从后向前递归
	public static ListNode reverseList2(ListNode head) {
		 //边缘条件判断
		 if(head == null) {
			 return null;
		 }
		 if(head.next == null) {
			 return head;
		 }
		 //递归调用,翻转第二个结点开始往后的链表
		 ListNode last = reverseList2(head.next);//可以想到last的第一个值为链表的末尾
		 //反转头结点与第二个结点的指向,这么理解:(head.next).next = head 就是调换第二个元素与第一个元素指针方向
		 head.next.next = head;
		// 此时的 head 节点为尾节点,next 需要指向 NULL
        head.next = null;
        return last;	 
		 
	 }
	 
	 
	
}

class ListNode {
	 
	 int val;
	 ListNode next;
	public ListNode(int val) {
		super();
		this.val = val;
	}
	@Override
	public String toString() {
		return "ListNode [val=" + val + ", next=" + next + "]";
	}
	
	 
}



//从后向前递归方法说明在这里插入图片描述在这里插入图片描述

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

DZSpace

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值