内容
反转链表。
针对的是不带头节点的单链表。
三指针法
给你单链表的头节点 head
,请你反转链表,并返回反转后的链表。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
|
class Solution { public: ListNode* reverseList(ListNode* head) { if (head == nullptr || head->next == nullptr) return head; ListNode * cur = head; ListNode * prev = nullptr; while (cur != nullptr) { ListNode * tmp = cur->next; cur->next = prev; prev = cur; cur = tmp; } return prev; } };
|
头插法(双指针法)
需要构建一个虚拟头节点。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| class Solution { public: ListNode* reverseList(ListNode* head) { if (head == nullptr || head->next == nullptr) return head; ListNode * headNode = new ListNode(0, head); ListNode * cur = head; ListNode * tmp = nullptr; headNode->next = nullptr; while (cur != nullptr) { tmp = cur; cur = cur->next; tmp->next = headNode->next; headNode->next = tmp; } head = headNode->next; delete headNode; return head; } };
|