class Solution {
public ListNode reverseList(ListNode head) {
if(head==null||head.next==null){
return head;
}
ListNode p1=head,p2=p1.next,p3=null;
while(p2!=null){
p3=p2.next;
p2.next=p1;
p1=p2;
p2=p3;
}
head.next=null;
return p1;
}
}
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/0086ad098ffd2f289879b3879b4d1739.png)
public ListNode reverseList(ListNode head) {
if(head==null||head.next==null){
return head;
}
ListNode tmp=head;
Stack<ListNode> stack=new Stack<>();
while(tmp!=null){
stack.push(tmp);
tmp=tmp.next;
}
ListNode result;
tmp=stack.pop();
result=tmp;
while(!stack.isEmpty()){
tmp.next=stack.pop();
tmp=tmp.next;
}
tmp.next=null;
return result;
}