class Solution {
public:
ListNode* reverseList(ListNode* head) {
ListNode* prev = nullptr;//定义前节点和当前节点
ListNode* curr = head;
while (curr) {
ListNode* next = curr->next
curr->next = prev;
prev = curr;
curr = next;
}
return prev;//循环结束,返回prev节点即可,不返回curr节点因为while循环退出时curr已经变为空节点了
}
};
class Solution {
public:
ListNode* reverseList(ListNode* head) {
if (head == NULL || head->next == NULL) // 空链或只有一个结点,直接返回头指针
{
return head;
}
else // 有两个以上结点
{
ListNode *new_head = reverseList(head->next); // 反转以第二个结点为头的子链表
// head->next 此时指向子链表的最后一个结点
// 将之前的头结点放入子链尾
head->next->next = head;
head->next = NULL;
return new_head;
}
}
};