设置三个指针,一个指头,一个指投next,一个指向头next->next,然后开始反转。
/** * 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 head; if(head->next==NULL) return head; ListNode *p,*q,*r; p=head; q=head->next; r=q->next; p->next=NULL; while(q!=NULL){ q->next=p; p=q; q=r; if(r!=NULL) r=r->next; } return p; } };执行用时 : 16 ms, 在Reverse Linked List的C++提交中击败了93.68% 的用户 内存消耗 : 9.4 MB, 在Reverse Linked List的C++提交中击败了5.08% 的用户