1.保存当前节点的next节点
2.修改当前节点next节点为pre(初值为null,因为反转后第一个节点的next节点为null)
3.将当前节点存进pre
4.进入next节点并循环
注意:循环结束后,还需要再赋一次值,因为在倒数第二个节点的next修改后,循环就终止了,还需将最后一个节点next修改。
public class Solution {
public ListNode ReverseList(ListNode head) {if(head==null) return null;
ListNode pre=null,nex=null;
while(head.next!=null){
nex=head.next;
head.next=pre;
pre=head;
head=nex;
}
head.next=pre;
return head;
}
}