反转一个单链表。
我的想法是定义三个,前,中,后,节点。不断的更改节点的指向,三个节点并不断的向后移位,最终遍历完成。
/**
* 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==nullptr)
{
return nullptr;
}
ListNode *ne=head->next;
ListNode *cur=head;
ListNode*pre=nullptr;
while(cur!=nullptr)
{
cur->next=pre;
pre=cur;
cur=ne;
if(ne!=nullptr)
{
ne=ne->next;
}
}
return pre;
}
};