1.从尾到头打印链表
用栈来辅助,压入栈,再输出
class Solution {
public:
vector<int> reversePrint(ListNode* head) {
vector<int> res;
stack<int> s; //辅助栈
ListNode* cur = head;
while(cur){
s.push(cur->val);
cur=cur->next;
}
while(!s.empty()){
res.push_back(s.top());
s.pop();
}
return res;
}
};
2.反转链表
遍历链表,将链表的后一个节点的指针指向前一个节点,为了更改之后,还要保存后一个节点的地址,cur = next。
class Solution {
public:
ListNode* reverseList(ListNode* head) {
//修改指针指向
ListNode* cur = head;
ListNode* pre = nullptr;
while(cur){
ListNode* next = cur->next;//保存后一个的地址
cur->next = pre;
pre = cur;
cur = next;
}
return pre;
}
};
3.带有随机指针链表的深拷贝
因为随机指针的存在,有可能指向的节点还未创建;用哈希表记录当前节点的对应新节点的创建情况,检查(当前节点的next节点)和(当前节点random指向节点),如果两个节点没有没创建,立刻递归进行创建。当拷贝完成,回到当前拷贝层,则需要考虑节点可能会被多个节点指向的情况,所以要检查当前节点是否被拷贝过。在实际操作中,还要考虑空节点的情况。
class Solution {
public:
unordered_map<Node*, Node*> cachedNode;//存放的是原链表节点,和新节点
Node* copyRandomList(Node* head) {
while(!cachedNode.count(head)){//当前节点是否被创建
if(head == nullptr){
return nullptr;
}
Node* headNew = new Node(head->val);
cachedNode[head] = headNew;
headNew->next = copyRandomList(head->next);//回溯到后继节点
headNew->random = copyRandomList(head->random);//回溯到random节点
}
return cachedNode[head];
}
};