public ListNode reverseList(ListNode head) {
if (head == null || head.next == null) return head;
ListNode newHead = null;//创建新链表
while(head != null){
ListNode oldnode = head;//保存链表中头节点
head = head.next;//摘除链表中的头结点
oldnode.next = newHead;//设置被摘除的节点的下一个节点为新链表的头节点
newHead = oldnode;//被摘除的节点作为新链表的头节点,插入新链表
}
return newHead;//返回新链表
}
https://leetcode-cn.com/problems/reverse-linked-list/submissions
public ListNode reverseList(ListNode head) {
if (head == null || head.next == null) return head;
ListNode oldNode = reverseList(head.next);
head.next.next = head;
head.next = null;
return oldNode;
}