class Solution {
public ListNode reverseList(ListNode head) {
ListNode curr = head;
Stack<ListNode> stack=new Stack<>();
// 所有节点入栈
while (curr != null) {
stack.push(curr);
curr = curr.next;
}
if(stack.empty()){
return null;
}
curr=stack.pop();//5
ListNode p =curr;
while (!stack.empty()) {
p.next = stack.pop();
p=p.next;
}
p.next=null;
return curr;
}
}
class Solution {
public ListNode reverseList(ListNode head) {
ListNode p = null;
//在p链表前添加
while (head!= null){
ListNode node = head.next;
head.next=p;
p=head;
head=node;
}
return p;
}
}
3、递归
class Solution {
public ListNode reverseList(ListNode head) {
if (head == null || head.next == null) {
return head;
}
ListNode newHead = reverseList(head.next);
head.next.next = head;
head.next = null;
return newHead;
}
}