方法一:
用栈实现:
class Solution {
public ListNode reverseList(ListNode head) {
Stack<ListNode> stack=new Stack<>();
while(head!=null){
stack.push(head);
head=head.next;
}
ListNode node = new ListNode(0);
head = node;
while(!stack.isEmpty()){
node.next=stack.pop();
node=node.next;
}
node.next=null;
return head.next;
}
}
方法二:
递归实现:
class Solution {
public ListNode reverseList(ListNode head) {
if(head==null)return head;
if(head.next==null)return head;
ListNode node = reverseList(head.next);
head.next.next = head;
head.next = null;
return node;
}
}
方法三:
迭代双指针:
class Solution {
public ListNode reverseList(ListNode head) {
ListNode ans =null;
while(head != null){
ListNode tmp=head.next;
head.next=ans;
ans=head;
head=tmp;
}
return ans;
}
}