題目:定義一個函數,輸入一個鏈表的頭節點,反轉該鏈表並輸出反轉後鏈表的頭節點。ide
示例:函數
輸入: 1->2->3->4->5->NULL 輸出: 5->4->3->2->1->NULL
反轉一個單鏈表,首先咱們想到經典的三指針法。定義三個指針,遍歷鏈表的指針pre,指向當前元素前一個元素的指針cur,cur所指向元素的下一個元素的指針ptr。而後更新指針內容,畫圖而後整理思路很快就寫出代碼:因此作鏈表這一類題必定要畫圖
3d
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: ListNode* reverseList(ListNode* head) { if(head==NULL) return NULL; ListNode* cur = NULL, *pre = head; ListNode* ptr; while(pre != NULL) { ptr = pre->next; pre->next = cur; cur = pre; pre = ptr; } return cur; } };
class Solution { public: ListNode* reverseList(ListNode* head) { if(head==NULL) return NULL; ListNode* cur = head; ListNode* ptr; while(head->next != NULL) { ptr = head->next->next; head->next->next = cur; cur = head->next; head->next = ptr; } return cur; } };