Java for LeetCode 206 Reverse Linked List

时间:2024-10-06 21:07:08

Reverse a singly linked list.

解题思路:

用Stack实现,JAVA实现如下:

    public ListNode reverseList(ListNode head) {
if(head==null)
return null;
Stack<ListNode> stack =new Stack<ListNode>();
ListNode temp=head;
while(temp!=null){
stack.push(temp);
temp=temp.next;
}
head=stack.pop();
temp=head;
while(!stack.isEmpty()){
temp.next=stack.pop();
temp=temp.next;
}
temp.next=null;
return head;
}