题目部分
24.两两交换链表元素
看了视频以后一遍写过
class Solution {
public:
ListNode* swapPairs(ListNode* head) {
ListNode* dummyNode = new ListNode;
dummyNode->next = head;
ListNode* cur = dummyNode;
while(cur->next!=nullptr&&cur->next->next!=nullptr){
ListNode* tmp = cur->next;
cur->next = tmp->next;
tmp->next = tmp->next->next;
cur->next->next = tmp;
cur = tmp;
}
return dummyNode->next;;
}
};
19.删除链表倒数第n个元素
一开始写不小心漏了把虚拟头结点指向头结点
class Solution {
public:
ListNode* removeNthFromEnd(ListNode* head, int n) {
ListNode* dummyNode = new ListNode;
dummyNode->next = head;
ListNode* fast = dummyNode;
ListNode* slow = dummyNode;
++n;
while(n--&&fast!=nullptr){
fast = fast->next;
}
while(fast!=nullptr){
fast = fast->next;
slow = slow->next;
}
ListNode* tmp = slow->next;
slow->next = tmp->next;
delete tmp;
return dummyNode->next;
}
};
面试题02.07
这题一下没啥思路,看答案做的,要注意值相同并非结点相同,要直接比较指针
class Solution {
public:
ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
int lena=0,lenb=0;
ListNode* curA = headA;
ListNode* curB = headB;
while(curA!=NULL){
curA = curA->next;
lena++;
}
while(curB!=NULL){
curB = curB->next;
lenb++;
}
curA = headA;
curB = headB;
if(lenb>lena){
swap(lena,lenb);
swap(curA,curB);
}
// 求长度差
int gap = lena - lenb;
// 让curA和curB在同一起点上(末尾位置对齐)
while (gap--) {
curA = curA->next;
}
// 遍历curA 和 curB,遇到相同则直接返回
while (curA != NULL) {
if (curA == curB) {
return curA;
}
curA = curA->next;
curB = curB->next;
}
return NULL;
}
};
142.环形链表入口
看了一遍视频,解析了一下思路,确实这个自己没办法想到
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode *detectCycle(ListNode *head) {
ListNode* fast = head;
ListNode* slow = head;
while(fast!=NULL&&fast->next!=NULL){
fast = fast->next->next;
slow = slow->next;
if(fast == slow){
ListNode* index1 = fast;
ListNode* index2 = head;
while(index1!=index2){
index1 = index1->next;
index2 = index2->next;
}
return index1;
}
}
return NULL;
}
};