刷题_反转链表

内容

反转链表。

针对的是不带头节点的单链表。

三指针法

给你单链表的头节点 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
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
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;
}
};

Cpp_引用

引用

引用的作用是给变量起一个别名。

引用的地址常性

1
2
3
4
5
6
7
int main()
{
int a2 = 9;
int a = 10;
int& b = a;
b = a2; // a
}

在定义引用时,必须指定一个被引用者(地址)。一旦定义成功,在其生命期中,就不可更换地址了。这是引用的地址常性。

相当于int & b = a在本质上是int * const b = &a

但是这与引用的该地址上的内存数据的常性不冲突。如果需要赋予数据常性,则仍需修饰const:int const & b = a。此时,就无法通过引用b去修改内存上的数据值了。