反转一个单链表。
示例:
输入: 1->2->3->4->5->NULL
输出: 5->4->3->2->1->NULL
/**
* 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)||(head->next=NULL)) return head;
ListNode* pre=NULL;
ListNode* cur=head;
ListNode* temp;
while(cur!=NULL){
temp=cur->next; //temp存放当前结点的下一结点的地址
cur->next=pre; //当前结点指向前一个结点
pre=cur; //pre往前走一个结点
cur=temp; //cur也走到下一个结点
//重复上述步骤
}
return pre; //最后pre走到正向的最后一个结点,即反向链表的第一个结点,所以返回pre
}
};