反轉一個單鏈表。
示例:
輸入: 1->2->3->4->5->NULL 輸出: 5->4->3->2->1->NULL
使用迭代方法,代碼如下:
/** * Definition for singly-linked list. * struct ListNode { * int val; * struct ListNode *next; * }; */ struct ListNode* reverseList(struct ListNode* head){ if (head == NULL || head->next == NULL) return head; struct ListNode *pre = head; struct ListNode *cur = head->next; struct ListNode *tmp = head->next->next; while(cur) { tmp = cur->next; cur->next = pre; pre = cur; cur = tmp; } head->next = NULL; return pre; }
遞歸方法如下:
struct ListNode* reverseList(struct ListNode* head){ if (head == NULL || head->next == NULL) return head; else { struct ListNode *newhead = reverseList(head->next); head->next->next = head; head->next = NULL; return newhead; } }
總結下,遞歸的寫法,整體來看,遞歸可以分成兩個部分,一個是,對最里層的遞歸進行判斷,那么對於這道題,最里層的遞歸就是當head為空,或者head->next為空。然后寫第二個部分,從最外層開始,並且假設,剩余的部分傳入遞歸函數返回的為已經反轉的鏈表,然后做剩余的部分。遞歸函數就是要注意一個頭一個尾,然后中間部分由遞歸完成就可以了。