力扣(LeetCode)官网 - 全球极客挚爱的技术成长平台
使用栈实现
public ListNode reverseList(ListNode head) {
if (head == null || head.next == null) return head;
Stack stack = new Stack();
while (head != null) {
stack.push(head);
head = head.next;
}
ListNode newNode = (ListNode) stack.pop();
ListNode curNewNode = newNode;
//这里对栈进行反转操作
while (stack.size() != 0) {
ListNode data = (ListNode) stack.pop();
curNewNode.next = data;
curNewNode = curNewNode.next;
}
curNewNode.next = null;
return newNode;
}
循环实现
public ListNode reverseList(ListNode head) {
if (head == null || head.next == null) return head;
ListNode newNode = null;
while(head != null) {
//记录后面的节点
ListNode cur = head.next;
//把head指向空,也就是newNode
head.next = newNode;
//再把newHead = head,这样是为了在下一次循环中后面的节点可以指向前面的节点
newNode = head;
//最后把head指向cur即可
head = cur;
}
return newNode;
}
递归实现
public ListNode reverseList(ListNode head) {
if(head == null || head.next == null) return head;
ListNode linked = reverseList(head.next);
//这里会拿到倒数第二个节点
head.next.next = head;
head.next = null;
return linked;
}