【java】链表的逆置

逆置链表

方法1:

1.定义一个新链表,一开始为null; Node newNode=null;//newNode有两层含义,1).新链表的第一个结点,2).代表着整个链表

2.循环cur,不为空

3.因为一会cur.next会变化,所以先将其保存起来 Node next=cur.next

4.进行头插 cur.next=newNode; newNode=cur;

5.使cur往后遍历 cur=next;

6.返回新链表的第一个结点 return newNode;

方法2:

1.创建两个结点,n1=null; n2=head;

2.n2不为空时

3.创建一个结点n3=n2.next;

4.让n2.next=n1;将链表逆置

5.走循环,n1=n2;n2=n3;

6.最后返回n1;

注意:不管什么方法,开头一定要判断head是否为null

//将链表逆置
	public static Node reverseList(Node head){
		if(head==null){
			return null;
		}
		Node newNode=null;
		Node cur=head;
		while(cur!=null){
			Node next=cur.next;
			cur.next=newNode;
		        newNode=cur;
			cur=next;
		}
		return newNode;
	}
	//将链表逆置
	public static Node reverseList1(Node head){
		if(head==null){
			return null;
		}
		Node n1=null;
		Node n2=head;
		while(n2!=null){
			Node n3=n2.next;
			n2.next=n1;
			n1=n2;
			n2=n3;
		}
		return n1;
	}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值