递归解决方案
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;
}
- 相信函数能返回后面结点反转之后的新头结点
- 那么返回的新头结点指向的是head.next
- 再令head.next.next指向head,并将head.next置空即可
- 避免无限递归,寻找递归结束条件
- 问题解决
迭代解决方案
public ListNode reverseList(ListNode head) {
ListNode newhead=null;
while (head!=null){
ListNode temp = head.next;
head.next = newhead;
newhead = head;
head = temp;
}
return newhead;
}
- 设定while循环条件
- 再定义暂存变量temp,暂存head.next,避免找不到下一结点
- head.next指向newhead,newhead再指向head,完成对newhead的头插入
- 令head指向temp,即指向下一结点
- 循环完成上述过程,即可反转链表