LeetCode
1. 基于头插法的迭代:
1 public ListNode reverseList(ListNode head) { 2 if(head == null) return null; 3 ListNode res = new ListNode(0); 4 res.next = head; 5 ListNode cur = head; 6 while(cur.next != null){ 7 ListNode tmp = cur.next; 8 cur.next = tmp.next; 9 tmp.next = res.next; 10 res.next = tmp; 11 } 12 return res.next; 13 }
2. 就地逆置的简洁迭代(elegant)
1 public ListNode reverse(ListNode head){ 2 ListNode prev = null; 3 while(head != null){ 4 ListNode next = head.next; 5 head.next = prev; 6 prev = head; 7 head = next; 8 } 9 return prev; 10 }
3. 递归
1 ListNode* reverseList(ListNode* head) { 2 if (!head || !(head -> next)) return head; 3 ListNode* node = reverseList(head -> next); 4 head -> next -> next = head; 5 head -> next = NULL; 6 return node; 7 }