leetcode 206.反转链表

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    ListNode* reverseList(ListNode* head) {
        if(head==NULL||head->next==NULL) return head;
        ListNode* cur=head;
        ListNode* p=NULL;
        ListNode* temp=cur->next;
        while(temp!=NULL){
            cur->next=p;
            p=cur;
            cur=temp;
            temp=temp->next;

        }
        cur->next=p;
        return cur;
    }
};

逐位向前反转next指针

你可能感兴趣的:(leetcode,链表,算法)