题目:

/**
 * 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) {
        ListNode* temp;          //采用双指针法,指针作用域要在循环体外
        ListNode* cur=head;
        ListNode* pre=NULL;
        while(cur){
            temp=cur->next;      //记录下一个节点
            cur->next=pre;       //改变当前指针的方向
            pre=cur;             //更新前一个指针
            cur=temp;            //更新当前指针
        }
        return pre;              //最后一个不为空的节点被赋予给指针pre
    }
};
posted on 2023-07-20 21:28  孜孜不倦fly  阅读(7)  评论(0)    收藏  举报