Reverse Linked List
两种做法,都要考虑好结尾处和怎么连接的
iteratively
if(head ==null || head.next ==null) return head; ListNode h = new ListNode(-1); h.next = head; ListNode n = head.next; while(n!=null){ ListNode t = n.next; n.next = h.next; h.next = n; head.next = t; // must connect the dangling pointer to the new-end(head) n = t; } return h.next;
recursively
// ref http://stackoverflow.com/questions/354875/reversing-a-linked-list-in-java-recursively public ListNode reverseList(ListNode head) { if(head ==null || head.next ==null) return head; ListNode secondH = head.next; ListNode newH = reverseList(secondH); head.next = null; //!!!! must secondH.next = head; return newH;