题目

代码
法一 迭代
class Solution {
public ListNode reverseList(ListNode head) {
ListNode pre =null;
ListNode cur = head;
while(cur!=null) {
ListNode nextTemp = cur.next;
cur.next = pre;
pre = cur;
cur = nextTemp;
}return pre;
}
}
法二 栈实现
class Solution {
public ListNode reverseList(ListNode head) {
Stack<ListNode> stack = new Stack<>();
ListNode start = new ListNode(0, new ListNode(0));
ListNode temp = start;
while (head != null) {
stack.push(head);
head = head.next;
}
while (!stack.isEmpty()) {
temp.next = stack.pop();
temp = temp.next;
}
temp.next = null;
return start.next;
}
}
结果

