单链表的反转,每次循环需要四步骤。
public ListNode reverse(ListNode head) { if(head == null || head.next == null) { return head; } ListNode pPre = head; ListNode pCurr = head.next; ListNode pNext = null; head.next = null; while(pCurr != null) { pNext = pCurr.next; pCurr.next = pPre; pPre = pCurr; pCurr = pNext; } return pPre; }
public static ListNode reverse(ListNode head) { if(head == null || head.next == null) { return head; } ListNode pPre = new ListNode(0); pPre.next = head; ListNode pCurr = head, pNext = null; while(pCurr != null) { pNext = pCurr.next; pCurr.next = pPre; pPre = pCurr; pCurr = pNext; } head.next = null;//head最后再赋值为null return pPre; }