面試中常常遇到反轉單鏈表,特此總結。面試
ListNode* reverseListRecursive(ListNode *head) { if(head == NULL || head->next == NULL) return head; ListNode *newHead = reverseListRecursive(head->next); head->next->next = head; head->next = NULL; return newHead; }
算法執行過程以下算法
將頭結點後面的結點經過頭插法一個個地插入到鏈表前面。spa
ListNode* reverseList(ListNode *head) { if(head == NULL || head->next == NULL) return head; ListNode *newHead = NULL; ListNode *p = head; while (p != NULL) { ListNode *tmp = p; p = p->next; tmp->next = newHead; newHead = tmp; } return newHead; }
算法執行流程以下code