反转链表
题目要求:
题目思路:
刚开始想以暴力解决,新建一个链表,接着不断地头插。但实践下来发现新建的节点总是会被覆盖。所以听课后采用双指针解法。
因为是第一遍,所以递归的用法暂时不理解,也没看。
对于双指针而言,就需要有一个额外的临时指针存第n+2个节点的地址。
不过(2024年5月16日)暂时不理解的是,为什么我的思路不可以……等二刷时候再看。
代码:
ListNode* reverseList(ListNode* head) {
ListNode* cur = head;
ListNode* pre = NULL;
while(cur){
ListNode *tempNode = cur->next;
cur->next = pre;
pre = cur;
cur=tempNode;
}
return pre;
}
此时不需要虚拟头节点。
什么时候需要虚拟头节点?什么时候不需要?需要解决的问题
交换链表节点
题目要求:
题目思路:其实自己的问题还是在于没有把链表连起来。两个元素交换后,会导致节点的丢失。现在想想,对应的指针没有明确。
代码:
ListNode* swapPairs(ListNode* head) {
/*
ListNode* cur = head;
if ( cur == NULL || cur->next == NULL ) {
return head;
}
while (cur != NULL && cur->next != NULL) {
int temp = cur->val;
cur->val = cur->next->val;
cur->next->val = temp;
cur = cur->next->next;
}
return head;
*/
ListNode* virHead = new ListNode(0);
virHead->next = head;
ListNode* cur = virHead;
// 如果没有元素,或者只有一个元素,直接返回就行。
if (cur == NULL || cur->next == NULL) {
return head;
}
// ListNode *tail = cur->next;
while (cur->next != NULL && cur->next->next != NULL) {
ListNode* temp = cur->next;
ListNode* mp = cur->next->next->next;
cur->next = cur->next->next;
cur->next->next = temp;
cur->next->next->next = mp;
cur = cur->next->next;
}
head =virHead->next;
delete virHead;
return head;
}