DAY4 - 24. 两两交换链表中的节点 ,19.删除链表的倒数第N个节点, 面试题02.07.链表相交,142.环形链表II
24. 两两交换链表中的节点
要画图,不然会乱。
class Solution {
public:
ListNode* swapPairs(ListNode* head) {
ListNode* fhead=new ListNode();
fhead->next=head;
ListNode* p=fhead;
while(p->next&&p->next->next){
ListNode* n1=p->next;
ListNode* n2=p->next->next;
p->next=n2;
n1->next=n2->next;
n2->next=n1;
p=p->next->next;
}
ListNode* res=fhead->next;
delete fhead;
return res;
}
};
19.删除链表的倒数第N个节点
这道题还有点印象,用双指针
一样的,画个图就清楚了。
class Solution {
public:
ListNode* removeNthFromEnd(ListNode* head, int n) {
ListNode* fhead=new ListNode();
fhead->next=head;
ListNode* last=fhead;
ListNode* ln=fhead;
for(int i=n;i>0;i--){
last=last->next;
}
while(last->next){
last=last->next;
ln=ln->next;
}
ListNode* temp=ln->next;
ln->next=temp->next;
delete temp;
return fhead->next;
}
};
面试题02.07.链表相交
如果有交点,则尾端肯定对齐。因为不涉及增删操作,所以可以不用设置 fhead
(但我还是写了fhead)
class Solution {
public:
ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
ListNode* fheadA = new ListNode();
ListNode* fheadB = new ListNode();
fheadA->next = headA;
fheadB->next = headB;
int lenA = 0, lenB = 0;
for (ListNode* a = fheadA; a != NULL; a = a->next) lenA++;
for (ListNode* b = fheadB; b != NULL; b = b->next) lenB++;
if (lenA == 0 || lenB == 0) return NULL;
ListNode* a = headA;
ListNode* b = headB;
if (lenA > lenB) {
for (; lenA > lenB; lenA--) a = a->next;
} else {
for (; lenB > lenA; lenB--) b = b->next;
}
while (a != NULL && b != NULL) {
if (a == b) return a;
a = a->next;
b = b->next;
}
return NULL;
}
};
浙公网安备 33010602011771号