思路1:遍历链表,将链表的所有元素存入一个栈中,从栈中取出元素时,依次得到的就是原链表从尾到头的节点。代码如下:
/*
public class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}*/
import java.util.Stack;
public class Solution {
public ListNode ReverseList(ListNode head) {
if(head==null){
return null;
}
Stack<ListNode> sta = new Stack<ListNode>();
while(head!=null){
sta.push(head);
head = head.next;
}
ListNode newhead = sta.pop(); //指针node
ListNode resulthead = newhead;
while(!sta.isEmpty()){
newhead.next = sta.pop();
newhead = newhead.next;
}
newhead.next = null;
return resulthead;
}
}
思路2:依次遍历所有节点,将所有节点的next指向前一个节点,代