(2)链表(简单)
剑指 Offer 06. 从尾到头打印链表
【题目描述】: 输入一个链表的头节点,从尾到头反过来返回每个节点的值(用数组返回)。
【分析】 (遍历链表)O(n)
单链表只能从前往后遍历,不能从后往前遍历
因此从前往后遍历一遍输入的链表,将结果记录在答案数组中,最后再将得到的数组逆序即可。
【时间复杂度】
链表和答案数组仅被遍历了常数次,所以总时间复杂度时O(n)
【代码】
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
vector<int> reversePrint(ListNode* head) {
vector<int> res;
while(head){
res.push_back(head->val);
head = head->next;
}
reverse(res.begin(),res.end());
return res;
}
};
剑指 Offer 24. 反转链表
【题目描述】: 定义一个函数,输入一个链表的头节点,反转该链表并输出反转后链表的头节点。
【分析】:
解题思路:
- 定义两个指针,pre和cur; pre在前cur在后
- 每次让pre的next指向cur,实现一次局部反转
- 局部反转完成后,pre和cur同时往前移动一个位置
- 循环上述过程,直至pre达到链表尾部
【代码】
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* reverseList(ListNode* head) {
ListNode* cur = nullptr,*pre = head;
while(pre){
auto temp = pre->next;
pre->next = cur;
cur = pre;
pre = temp;
}
return cur;
}
};
【法二】:递归
【分析】
- 使用递归函数,一直递归到链表的最后一个结点,该节点就是反转后的头节点,记作ret;
- 之后每次函数在返回的过程中,让当前的节点的下一个节点的next指针指向当前节点
- 同时让当前节点的next指针指向nullptr,从而实现从链表尾部开始的局部反转;
- 当递归函数全部出栈后,链表反转完成。
【代码】
class Solution{
public:
ListNode* reverseList(ListNode* head){
if(head == nullptr || head->next == nullptr){
return head;
}
auto ret = reverseList(head->next);
head->next->next = head;
head->next = nullptr;
return ret;
}
}
剑指 Offer 35. 复杂链表的复制
【题目描述】: 请实现 copyRandomList 函数,复制一个复杂链表。在复杂链表中,每个节点除了有一个 next 指针指向下一个节点,还有一个 random 指针指向链表中的任意节点或者 null。
【代码】
/*
// Definition for a Node.
class Node {
public:
int val;
Node* next;
Node* random;
Node(int _val) {
val = _val;
next = NULL;
random = NULL;
}
};
*/
class Solution {
public:
Node* copyRandomList(Node* head) {
unordered_map<Node*,Node*>hash;
hash[nullptr] = nullptr;
auto dump = new Node(-1),tail = dump;
while(head){
if(!hash.count(head)) hash[head] = new Node(head->val);
if(!hash.count(head->random))
hash[head->random] = new Node(head->random->val);
tail->next = hash[head];
tail->next->random = hash[head->random];
tail = tail->next;
head = head->next;
}
return dump->next;
}
};
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/fu-za-lian-biao-de-fu-zhi-lcof
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。