LeetCode 206 反转链表
解答
// 定义链表节点结构体
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(nullptr) {}
};
// 迭代方法反转链表
ListNode* reverseList(ListNode* head) {
ListNode *prev = nullptr;
ListNode *current = head;
while (current != nullptr) {
ListNode *nextTemp = current->next; // 保存当前节点的下一个节点
current->next = prev; // 反转当前节点的指针
prev = current; // 前移prev
current = nextTemp; // 前移current
}
return prev; // 新的头节点
}