同从头到尾打印链表(两者区别,反转链表返回节点,从头到尾打印链表返回数组) 从头到尾打印链表:https://blog.nowcoder.net/n/1ed388edcf0b41a48c4b75404779fd7c
public class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}*/
public class Solution {
public ListNode ReverseList(ListNode head) {
//cur为当前节点
//nex保存当前节点的下一个节点
//pre已经反转节点的头节点
//判断不为空
if(head==null)
{
return head;
}
//初始化
ListNode cur=head;
ListNode nex=null;
ListNode pre=null;
while(cur!=null)
{
nex=cur.next;
cur.next=pre;
pre=cur;
cur=nex;
}
return pre;
}
}