合并链表
思路:两个链表,短的链表要向长的链表尾部对齐。此时不需要头节点,因为不需要操作,只需要遍历。
int getLen(ListNode* head) {
int num = 0;
ListNode* cur = head;
while (cur != NULL) {
num += 1;
cur = cur->next;
}
return num;
}
ListNode* getIntersectionNode(ListNode* headA, ListNode* headB) {
int numA = getLen(headA);
int numB = getLen(headB);
ListNode* curA = headA;
ListNode* curB = headB;
if (headA == headB) {
return headA;
}
if (numA > numB || numA == numB) {
for (int i = 0; i < numA; i++) {
if (i < numA - numB) {
curA = curA->next;
} else {
if (curA == curB) {
return curA;
} else {
curA = curA->next;
curB = curB->next;
}
}
}
} else {
for (int i = 0; i < numB; i++) {
if (i < numB - numA) {
curB = curB->next;
} else {
if (curA == curB) {
return curA;
} else {
curA = curA->next;
curB = curB->next;
}
}
}
}
return NULL;
}
删除倒数第K个链表元素
思路:
因为栓哥讲过,所以印象很深刻。用两个指针来分别指向末尾元素和倒数第二个元素就行。
此时需要虚拟头节点。
因为是倒数第k个,所以back指向倒数第k-1个节点,以保证链表断开。也就是说,cur指针和back指针之间要多隔一个元素。
cur最后要指向null,back最后要指向倒数第k+1(第k个节点的前面)个节点。
那么,最开始的时候,cur指向的是虚拟头节点。才能向后移动。
ListNode* removeNthFromEnd(ListNode* head, int n) {
int num = 0;
ListNode* virHead = new ListNode(0);
virHead->next = head;
ListNode* cur = virHead;
ListNode* back = NULL;
if (cur->next == NULL) {
return head;
// 表示一个元素都没有
}
while (cur != NULL) {
cur = cur->next;
// 如果到了那一步
if (back != NULL) {
back = back->next;
} else {
if (num == n) {
back = virHead;
} else {
num += 1;
}
}
}
// 当cur走到头,此时的back就是倒数第n-1个元素了
//ListNode* del_node = back->next;
ListNode* temp = back->next->next;
back->next = temp;
//delete del_node;
return virHead->next;
}