递归解决方案
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,即指向下一结点循环完成上述过程,即可反转链表