链表操作
遇到链表问题先在纸上画出结构
解题思路一
- 使用哈希表将新旧链表一一对应;
- 根据原链表的next和random指针来构建新链表的next和random指针
class Solution {
public: Node* copyRandomList(Node* head) {
if (head == NULL) return NULL;
unordered_map<Node*, Node*> mp;
Node* p = head;
while(p != NULL){
mp[p] = new Node(p->val);
p = p->next;
}
p = head;
while(p){
mp[p]->next = mp[p->next];
mp[p]->random = mp[p->random];
p = p->next;
}
return mp[head];
}
};
思路二
- 在原链表的基础上先复制next,A->B->C变成A->A->B->B->C->C
- 复制random指针
- 链表分离:head->next=head->next->next
class Solution {
public:
Node* copyRandomList(Node* head) {
if (head == NULL) return NULL;
Node* p = head;
while(p != NULL){
Node* cur = p->next;
p->next = new Node(p->val);
p->next->next = cur;
p = cur;
}
p = head;
while(p){
if (p->random != NULL){
p->next->random = p->random->next;
}
p = p->next->next;
}
p = head;
Node* newHead = new Node(0);
Node* cur = newHead;
while(p){
cur->next = p->next;
cur = cur->next;
p->next = cur->next;
p = p->next;
}
return newHead->next;
}
};
方法1:双指针反转
class Solution {
public:
ListNode* reverseList(ListNode* head) {
ListNode* pre = NULL;
ListNode* cur = head;
while(cur){
ListNode* pNext = cur->next;
cur->next = pre;
pre = cur;
cur = pNext;
}
return pre;
}
};
方法2:递归
引用自该网页,很全面全面的反转链表
class Solution {
public:
ListNode* reverseList(ListNode* head) {
if (head == NULL || head->next == NULL)
return head;
ListNode* p = reverseList(head->next);
head->next->next = head;
head->next = NULL;
return p;
}
};