解题思路
递归
public ListNode ReverseList(ListNode head) {
//递归终止条件:找到链表最后一个结点
if (head == null || head.next == null) {
return head;
}
//先反转后面的链表
ListNode newHead = ReverseList(head.next);
//将后一个链表结点指向前一个结点
head.next.next = head;
//将原链表中前一个结点指向后一个结点的指向关系断开
head.next = null;
return newHead;
}
迭代
public ListNode ReverseList(ListNode head) {
ListNode newList = new ListNode(-1);
while (head != null) {
ListNode next = head.next;
head.next = newList.next;
newList.next = head;
head = next;
}
return newList.next;
}