题目:定义一个函数,输入一个链表的头节点,反转该链表并输出反转后链表的头节点。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; } };