赞
踩
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 static ListNode reverseListIterative(ListNode head) { ListNode prev = null; //前指针节点 ListNode curr = head; //当前指针节点 ListNode next; //每次循环,都将当前节点指向它前面的节点 //然后当前节点和前节点后移 while (curr != null) { //临时节点,暂存当前节点的下一节点,用于后移 //因为接下来curr.next进行赋值后将会断链 next= curr.next; //将当前节点指向它前面的节点 curr.next = prev; //前指针后移 prev = curr; //当前指针后移 curr = next; } return prev; }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。