剑指 Offer 06. 从尾到头打印链表
输入一个链表的头节点,从尾到头反过来返回每个节点的值(用数组返回)。
示例 1:
输入:head = [1,3,2]
输出:[2,3,1]
方法一:遍历存一下然后翻转
/**
* 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!=NULL)
{
res.push_back(head->val);
head = head->next;
}
reverse(res.begin(),res.end());
return res;
}
};
方法二:用栈存一下然后出栈存一下
/**
* 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) {
stack<int> st;
vector<int> res;
while(head!=NULL)
{
st.push(head->val);
head = head->next;
}
while(!st.empty())
{
res.push_back(st.top());
st.pop();
}
return res;
}
};
剑指 Offer 24. 反转链表
定义一个函数,输入一个链表的头节点,反转该链表并输出反转后链表的头节点。
示例:
输入: 1->2->3->4->5->NULL
输出: 5->4->3->2->1->NULL
方法一:迭代法,创建三个指针pre,cur,next遍历一遍
/**
* 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* pre = NULL;
ListNode* cur = head;
while(cur!=NULL)
{
ListNode* next = cur->next;
cur->next = pre;
pre = cur;
cur = next;
}
return pre;
}
};
方法二:递归法
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* reverse(ListNode* pre,ListNode* cur)
{
if(cur==NULL) return pre;
ListNode* tmp = cur->next;
cur->next = pre;
return reverse(cur,tmp); //等价于 pre = cur, cur = tmp;
}
ListNode* reverseList(ListNode* head) {
return reverse(NULL,head);
}
};
剑指 Offer 35. 复杂链表的复制
请实现 copyRandomList 函数,复制一个复杂链表。在复杂链表中,每个节点除了有一个 next 指针指向下一个节点,还有一个 random 指针指向链表中的任意节点或者 null。
输入:head = [[7,null],[13,0],[11,4],[10,2],[1,0]]
输出:[[7,null],[13,0],[11,4],[10,2],[1,0]]
方法:哈希表+迭代
用一个哈希表记录原链表和新链表
遍历一遍原链表创建结点并建立哈希表,在遍历一遍把新链表的next和random指针连接到对应位置
/*
// 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) {
Node* cur = head;
unordered_map<Node*,Node*> map;
while(cur!=NULL)
{
map[cur] = new Node(cur->val);
cur = cur->next;
}
cur = head;
while(cur!=NULL)
{
map[cur]->next = map[cur->next];
map[cur]->random = map[cur->random];
cur = cur->next;
}
return map[head];
}
};