剑指 Offer 24. 反转链表 - 力扣(LeetCode) (leetcode-cn.com)
/** * 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* pre=nullptr; ListNode* cur=head; while(cur) { ListNode* nextnode=cur->next; cur->next=pre; pre=cur; cur=nextnode; } return pre; // if(head==NULL) return NULL; // if(head->next == NULL) return head; // ListNode* last = reverseList(head->next); // head->next->next = head; // head->next = NULL; // return last; } };
注释掉的是递归写法