反转链表
给你单链表的头节点 head ,请你反转链表,并返回反转后的链表。
输入:head = [1,2,3,4,5]
输出:[5,4,3,2,1]
示例 2:
输入:head = [1,2]
输出:[2,1]
代码
原地反转:
h和t之间是已经反转之后的链表起始和结束节点,p是下一个待插入的结点
h t p
每次取p插入到h之前,更新h,更新p
ListNode* reverseList(ListNode* head) {
if (head == nullptr)
return head;
else if (head->next == nullptr)
return head;
ListNode* h = head , * t = head;
ListNode* p = h->next;
while (p!=nullptr) {
t->next = p->next;
p->next = h;
h = p;
p = t->next;
}
return h;
}
```